繁体   English   中英

如何在 Java 中将带有嵌套列表的对象序列化为 JSON

[英]How to serialize Object with nested lists to JSON in Java

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

对象结构

  1. 一个包含Test列表的对象Subject
  2. 每个Test包含一个Question列表。
  3. 每个Question最后都包含对象AnswersContent
  4. 这个最终对象AnswersContent包含 4 个单独的String (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 以及我可以使用什么工具。

也许我只是使用错误的短语进行搜索。

尝试这个

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

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

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

另请参阅用户指南

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM