如何在Java中返回多个JSON项的列表

huangapple go评论87阅读模式
英文:

How to return a list of multiple JSON items in java

问题

我正在尝试弄清楚如何返回多个JSON项。目前,我能够返回单个JSON,如下所示:

{
    "result": {
        "userId": "abcde123",
        "telephoneNumber": "1-555-5555555"
    },
    "error": null
}

但我想返回多个JSON项,如下所示:

{
    "result": [
        {
            "userId": "abcde123",
            "telephoneNumber": "1-555-5555555"
        },
        {
            "userId": "fghi456",
            "telephoneNumber": "1-333-3333333"
        }
    ],
    "error": null
}

我可以将多个JSON项视为字符串,如下所示,但我想将其返回为多个JSON项,但我不知道如何做:

[LDAPModel(userId=abcde123, telephoneNumber=1-555-5555555), LDAPModel(userId=fghi456, telephoneNumber=1-333-3333333)]

我是Java的完全初学者,对Java的语法或了解不多。但我从SpringBoot获得了以下代码(包括下面的代码),我真的不理解它在做什么,因此我不知道如何创建一个列表的输出。

目前,我被提供了这个代码:

public Optional<LDAPModel> getDirectReports(String cdsID) {
    LdapQuery ldapQuery = LdapQueryBuilder.query()
            .searchScope(SearchScope.SUBTREE)
            .where("objectclass").is("person")
            .and("managerID").like(cdsID);

    List<LDAPModel> ldapModelList = ldapTemplate.search(ldapQuery, (Attributes attrs) ->
            LDAPModel.builder()
                    .userId(getValue(attrs, "userid"))
                    .telephoneNumber(getValue(attrs, "phoneNumber"))
                    .build());

    return ldapModelList.isEmpty() ? Optional.empty() : Optional.of(ldapModelList.get(0));
}

我尝试将其放入循环中(如上面注释掉的代码),但我不知道如何创建一个列表。我尝试删除get(0),但出现了语法错误... 我尝试了许多方法,但都没有帮助。

有人可以帮助吗?

更新/编辑:感谢大家的回答。我发布了一个后续问题在这里。如果有机会,请帮助我。谢谢。

英文:

I am trying to figure out how to return multiple JSON items. Right now I am able, to return a single JSON like so:

{
    &quot;result&quot;: {
        &quot;userId&quot;: &quot;abcde123&quot;,
        &quot;telephoneNumber&quot;: &quot;1-555-5555555&quot;
        },
    &quot;error&quot;: null
}

But I would like to return multiple JSON items, like so:

{
    &quot;result&quot;: {{
        &quot;userId&quot;: &quot;abcde123&quot;,
        &quot;telephoneNumber&quot;: &quot;1-555-5555555&quot;
        }
        {
        &quot;userId&quot;: &quot;fghi456&quot;,
        &quot;telephoneNumber&quot;: &quot;1-333-3333333&quot;
        }
        },
    &quot;error&quot;: null
}

I can view the multiple JSON items as string, like below, but I would like to return it as multiple JSON items, but I don't know how:

[LDAPModel(userId=abcde123, telephoneNumber=1-555-5555555), LDAPModel(userId=fghi456, telephoneNumber=1-333-3333333]

I am a complete beginner in Java, and I don't know the syntax or much in Java. But I was given these codes (including the one below) from SpringBoot; I really don't understand what it is doing, and so I have no idea how create an output of list.

Currently, this is what I was given:

public Optional&lt;LDAPModel&gt; getDirectReports(String cdsID) {
        LdapQuery ldapQuery = LdapQueryBuilder.query()
                .searchScope(SearchScope.SUBTREE)
                .where(&quot;objectclass&quot;).is(&quot;person&quot;)
                .and(&quot;managerID&quot;).like(cdsID);

        List&lt;LDAPModel&gt; ldapModelList = ldapTemplate.search(ldapQuery, (Attributes attrs) -&gt;
                LDAPModel.builder()
                        .userId(getValue(attrs, &quot;userid&quot;))
                        .telephoneNumber(getValue(attrs, &quot;phoneNumber&quot;))
                        .build());
//        for (int ii = 0; ii &lt; ldapModelList.size(); ii++) {
//            Optional.of(ldapModelList.get(ii));
//            ldapModelList.isEmpty() ? Optional.empty() : Optional.of(ldapModelList.get(ii));
//        }
        return ldapModelList.isEmpty() ? Optional.empty() : Optional.of(ldapModelList.get(0));
    }

I tried putting it in a loop (like in the commented out code above), but I don't know how create a list. I tried removing the get(0), but there was a syntax error... There are many things I tried, but it just did not help.

Anyone can help?

Update/Edit: Thank you all for your answers. I posted a follow up question [here](https://stackoverflow.com/questions/63276147/how-to-return-a-list-of-multiple-json-items-in-java-part-2 "How to return a list of multiple JSON items in java, part 2"). If you have a chance, please help me out. Thanks.

答案1

得分: 1

结构对我来说看起来很奇怪。您的结构看起来像您希望结果是一个对象数组:

{
    "result": [
        { "userId": "abcde123",
          "telephoneNumber": "1-555-5555555" },
        { "userId": "fghi456",
          "telephoneNumber": "1-333-3333333" }
        ],
    "error": null
}

使用一个合理的 JSON 库,那么 JSON 对象的 "result" 成员的值是一个 JSON 数组,然后您可以通过索引逐个提取每个元素,每个元素都是一个具有2个成员的 JSON 对象。

英文:

The structure looks strange to me. What you have looks like you want result to be an array of objects:

{
    &quot;result&quot;: [
        { &quot;userId&quot;: &quot;abcde123&quot;,
          &quot;telephoneNumber&quot;: &quot;1-555-5555555&quot; }
        { &quot;userId&quot;: &quot;fghi456&quot;,
          &quot;telephoneNumber&quot;: &quot;1-333-3333333&quot; }
        ],
    &quot;error&quot;: null
}

Given a reasonable JSON library, then the value of the "result" member of the JSON object is a JSON array, from which you can then pick out each element in turn by indexing, and each element is a JSON object with 2 members.

答案2

得分: 0

首先,我想指出你的JSON格式不正确。当你想在JSON中表示多个对象时,应该使用方括号,并用逗号分隔每个对象:

{
    "result": [
        {
          "userId": "abcde123",
          "telephoneNumber": "1-555-5555555"
        },
        {
          "userId": "fghi456",
          "telephoneNumber": "1-333-3333333"
        }
    ],
    "error": null
}

你的Java代码之所以在尝试移除 get(0) 时不起作用,是因为方法 public Optional<LDAPModel> getDirectReports(String cdsID) 返回一个 Optional<LDAPModel> 类型,而通过移除 get(0),实际上你试图返回一个 Optional<List<LDAPModel>>。如果你希望该方法返回一个列表而不是单个对象,你可以将返回类型更改为 Optional<List<LDAPModel>>,然后安全地移除 get(0)

public Optional<List<LDAPModel>> getDirectReports(String cdsID) {
        LdapQuery ldapQuery = LdapQueryBuilder.query()
                .searchScope(SearchScope.SUBTREE)
                .where("objectclass").is("person")
                .and("managerID").like(cdsID);

        List<LDAPModel> ldapModelList = ldapTemplate.search(ldapQuery, (Attributes attrs) ->
                LDAPModel.builder()
                        .userId(getValue(attrs, "userid"))
                        .telephoneNumber(getValue(attrs, "phoneNumber"))
                        .build());

        return ldapModelList.isEmpty() ? Optional.empty() : Optional.of(ldapModelList);
    }
英文:

First of all I would like to point out that your JSON isn't formatted properly. When you want to represent multiple objects in JSON you should use square brackets and separate each object with a comma:

{
    &quot;result&quot;: [
        {
          &quot;userId&quot;: &quot;abcde123&quot;,
          &quot;telephoneNumber&quot;: &quot;1-555-5555555&quot;
        },
        {
          &quot;userId&quot;: &quot;fghi456&quot;,
          &quot;telephoneNumber&quot;: &quot;1-333-3333333&quot;
        }
        ],
    &quot;error&quot;: null
}

The reason your Java code does not work when you try and remove get(0) is because the method public Optional&lt;LDAPModel&gt; getDirectReports(String cdsID) returns an Optional&lt;LDAPModel&gt; type and by removing get(0) your are effectively trying to return an Optional&lt;List&lt;LDAPModel&gt;&gt;. If you want the method to return a list instead of a single object you can change the return type to Optional&lt;List&lt;LDAPModel&gt;&gt; and then safely remove get(0).

public Optional&lt;List&lt;LDAPModel&gt;&gt; getDirectReports(String cdsID) {
        LdapQuery ldapQuery = LdapQueryBuilder.query()
                .searchScope(SearchScope.SUBTREE)
                .where(&quot;objectclass&quot;).is(&quot;person&quot;)
                .and(&quot;managerID&quot;).like(cdsID);

        List&lt;LDAPModel&gt; ldapModelList = ldapTemplate.search(ldapQuery, (Attributes attrs) -&gt;
                LDAPModel.builder()
                        .userId(getValue(attrs, &quot;userid&quot;))
                        .telephoneNumber(getValue(attrs, &quot;phoneNumber&quot;))
                        .build());

        return ldapModelList.isEmpty() ? Optional.empty() : Optional.of(ldapModelList);
    }

答案3

得分: 0

以下是您要翻译的代码部分:

我假设您已经成功获取了LDAPModel的列表/数组即List<LDAPModel> ldapModelList

如果是这样您只需要在您的getDirectReports方法中返回这个ldapModelList

public List<LDAPModel> getDirectReports(String cdsID) {
    LdapQuery ldapQuery = LdapQueryBuilder.query()
            .searchScope(SearchScope.SUBTREE)
            .where("objectclass").is("person")
            .and("managerID").like(cdsID);

    List<LDAPModel> ldapModelList = ldapTemplate.search(ldapQuery, (Attributes attrs) ->
            LDAPModel.builder()
                    .userId(getValue(attrs, "userid"))
                    .telephoneNumber(getValue(attrs, "phoneNumber"))
                    .build());
    return ldapModelList;
}

然后,只需使用您的库来返回JSON数组。我假设您使用Jackson。只需确保在LDAPModel中有以下内容:

  1. 获取器(getters)和设置器(setters)。
  2. 如果您添加了自己的带参数构造函数,请确保有空的构造函数。但如果您没有添加任何构造函数,那么无需添加默认的空构造函数,因为Java会自动为您创建它。

LDAPModel类如下所示:

public class LDAPModel {
    String userId;
    String telephoneNumber;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getTelephoneNumber() {
        return telephoneNumber;
    }

    public void setTelephoneNumber(String telephoneNumber) {
        this.telephoneNumber = telephoneNumber;
    }
}

关于使用Jackson进行对象到JSON字符串转换,我假设您已经知道如何操作,或者可以找到相关信息。

英文:

I assume you already managed to get all the list/array of LDAPModel i.e. List<LDAPModel> ldapModelList

If so, you just need to return this ldapModelList in your getDirectReports method.

public List&lt;LDAPModel&gt; getDirectReports(String cdsID) {
	LdapQuery ldapQuery = LdapQueryBuilder.query()
			.searchScope(SearchScope.SUBTREE)
			.where(&quot;objectclass&quot;).is(&quot;person&quot;)
			.and(&quot;managerID&quot;).like(cdsID);

	List&lt;LDAPModel&gt; ldapModelList = ldapTemplate.search(ldapQuery, (Attributes attrs) -&gt;
			LDAPModel.builder()
					.userId(getValue(attrs, &quot;userid&quot;))
					.telephoneNumber(getValue(attrs, &quot;phoneNumber&quot;))
					.build());
	return ldapModelList;
}

Then just use your library to return the json array. I suppose you use jackson.
Just make sure in LDAPModel you have

  1. getters and setters
  2. empty constructor if you add your own constructor having params. But if you don't add any constructor, then no need to add this default empty constructor as java will automatically create it for you.

LDAPModel class is as follows:

public class LDAPModel {
    String userId;
    String telephoneNumber;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getTelephoneNumber() {
        return telephoneNumber;
    }

    public void setTelephoneNumber(String telephoneNumber) {
        this.telephoneNumber = telephoneNumber;
    }
}

For the object to JSON string conversion using Jackson, I assume you already know it or can find out how.

huangapple
  • 本文由 发表于 2020年8月5日 07:04:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/63256209.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定