如何将List<JsonObject>转换为JsonArray在JAVA中

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

How to convert List<JsonObject> to JsonArray in JAVA

问题

我已经编写了一段代码,需要从一个“select * 查询”中创建一个JSON格式的输出。到目前为止,我能够获取以下输出,但我需要将其包装在“users”内:

{
  "displayName": "Tony Stark",
  "givenName": "Tony",
  "surname": "Stark"
},
{
  "displayName": "James Martin",
  "givenName": "James",
  "surname": "Martin"
}

我需要像这样的格式:

{
   "users": 
      [
            {
                  "displayName": "Tony Stark",
                  "givenName": "Toney",
                  "surname": "Stark"
            },
            {
                  "displayName": "James Martin",
                  "givenName": "James",
                  "surname": "Martin"
            }
      ]
}

请帮助我解决这个问题。

英文:

I have written a code, where I need to create a JSON format output from a "select * query". So far I am able to get the output like this, but I have to wrap it up inside "users"

{
  &quot;displayName&quot;: &quot;Tony Stark&quot;,
  &quot;givenName&quot;: &quot;Tony&quot;,
  &quot;surname&quot;: &quot;Stark&quot;
},
{
  &quot;displayName&quot;: &quot;James Martin&quot;,
  &quot;givenName&quot;: &quot;James&quot;,
  &quot;surname&quot;: &quot;Martin&quot;
}

I need something like this:

{
   &quot;users&quot;: 
      [
            {
                  &quot;displayName&quot;: &quot;Tony Stark&quot;,
                  &quot;givenName&quot;: &quot;Toney&quot;,
                  &quot;surname&quot;: &quot;Stark&quot;
            },
            {
                  &quot;displayName&quot;: &quot;James Martin&quot;,
                  &quot;givenName&quot;: &quot;James&quot;,
                  &quot;surname&quot;: &quot;Martin&quot;
            }
      ]
}

Please help me out in this.

答案1

得分: 1

是的,如果您创建一个名为"Users"的模型类,并正确映射它以及其属性,那么它将与您在截图中显示的内容完全一样。
附上参考模型类。

如何将List<JsonObject>转换为JsonArray在JAVA中

英文:

Yes it's possible if you create a model class named Users, map it properly along it with it's attributes so it will show exactly as shown by you in the screenshot.
Attaching reference model class.

如何将List<JsonObject>转换为JsonArray在JAVA中

答案2

得分: 0

以下是已经翻译好的部分:

"如果添加一个包装类并将其转换为JSON将会很容易。"

import java.util.List;

public class UserWrap {
    private List<User> users;

    public UserWrap(List<User> users) {
        this.users = users;
    }
}
英文:

It would be easy if add a wrap class and convert it to json

import java.util.List;

public class UserWrap {
    private List&lt;User&gt; users;

    public UserWrap(List&lt;User&gt; users) {
        this.users = users;
    }
}

huangapple
  • 本文由 发表于 2020年8月11日 14:10:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/63352447.html
匿名

发表评论

匿名网友

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

确定