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

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

How to convert List<JsonObject> to JsonArray in JAVA

问题

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

  1. {
  2. "displayName": "Tony Stark",
  3. "givenName": "Tony",
  4. "surname": "Stark"
  5. },
  6. {
  7. "displayName": "James Martin",
  8. "givenName": "James",
  9. "surname": "Martin"
  10. }

我需要像这样的格式:

  1. {
  2. "users":
  3. [
  4. {
  5. "displayName": "Tony Stark",
  6. "givenName": "Toney",
  7. "surname": "Stark"
  8. },
  9. {
  10. "displayName": "James Martin",
  11. "givenName": "James",
  12. "surname": "Martin"
  13. }
  14. ]
  15. }

请帮助我解决这个问题。

英文:

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"

  1. {
  2. &quot;displayName&quot;: &quot;Tony Stark&quot;,
  3. &quot;givenName&quot;: &quot;Tony&quot;,
  4. &quot;surname&quot;: &quot;Stark&quot;
  5. },
  6. {
  7. &quot;displayName&quot;: &quot;James Martin&quot;,
  8. &quot;givenName&quot;: &quot;James&quot;,
  9. &quot;surname&quot;: &quot;Martin&quot;
  10. }

I need something like this:

  1. {
  2. &quot;users&quot;:
  3. [
  4. {
  5. &quot;displayName&quot;: &quot;Tony Stark&quot;,
  6. &quot;givenName&quot;: &quot;Toney&quot;,
  7. &quot;surname&quot;: &quot;Stark&quot;
  8. },
  9. {
  10. &quot;displayName&quot;: &quot;James Martin&quot;,
  11. &quot;givenName&quot;: &quot;James&quot;,
  12. &quot;surname&quot;: &quot;Martin&quot;
  13. }
  14. ]
  15. }

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将会很容易。"

  1. import java.util.List;
  2. public class UserWrap {
  3. private List<User> users;
  4. public UserWrap(List<User> users) {
  5. this.users = users;
  6. }
  7. }
英文:

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

  1. import java.util.List;
  2. public class UserWrap {
  3. private List&lt;User&gt; users;
  4. public UserWrap(List&lt;User&gt; users) {
  5. this.users = users;
  6. }
  7. }

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:

确定