[英]How to serialize Object with nested lists to JSON in Java
我想从包含嵌套 ArrayLists 的对象创建 JSON。
Test
列表的对象Subject
。Test
包含一个Question
列表。Question
最后都包含对象AnswersContent
。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.