[英]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.