簡體   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