【问题标题】:How to serialize Object with nested lists to JSON in Java如何在Java中将带有嵌套列表的对象序列化为JSON
【发布时间】:2019-12-17 21:44:05
【问题描述】:

我想从包含嵌套 ArrayLists 的对象创建 JSON。

对象结构

  1. 一个对象Subject,包含Tests 的列表。
  2. 每个Test 都包含一个Questions 列表。
  3. 每个Question最终都包含对象AnswersContent
  4. 这个最终对象 AnswersContent 包含 4 个单独的 Strings(answerA、answerB、answerC、answerD)。

来源

public class Subject {

  private ArrayList<Test> tests = new ArrayList<Test>();
  //some other fields (String, int)
}
public class Test {

  public ArrayList<Question> test = new ArrayList<Question>();
  // some other fields (String, int)
}
public class Question {

  private AnswersContent answersContent;
  // some other fields (String, int)
}
public class AnswersContent {

  private String answerA;
  private String answerB;
  private String answerC;
  private String answerD;
}

所以我有嵌套的对象列表。 我不知道如何从中获取 JSON 以及我可以使用什么工具。

也许我只是用错误的词组搜索。

【问题讨论】:

  • 看看这个:JSON in Java.
  • 我喜欢gson。这很简单。
  • 大部分流行的JSON库(例如JacksonGsonorg.json)都可以做到这一点,你可以先学习“如何将对象转换为JSON”。
  • 既然您已经获得了一些图书馆推荐,您是否尝试过使用它们?然后,请edit您的问题并将您的尝试(将 JSON 输出)发布为minimal reproducible example!在此基础上,我们可以为您提供指导。

标签: java json serialization


【解决方案1】:

试试这个

public String getAsJsonString(){
     return new Gson().toJson(this);
}

您必须将此方法添加到“AnswersContent”类;

您也可以下载Gson jar file,或者如果您使用的是maven,请将其添加到您的 pom.xml 中

另见User Guide

【讨论】:

  • 发布 code-sn-ps 是一个好的开始。它总是有助于解释解决方案。尤其是在引入新库时(如Gson 此处),链接可能有助于下载或开始使用。
猜你喜欢
  • 1970-01-01
  • 2017-12-28
  • 2017-12-28
  • 2016-10-02
  • 2021-11-24
  • 1970-01-01
  • 1970-01-01
  • 2017-10-29
  • 1970-01-01
相关资源
最近更新 更多