将JSON列表转换为GSON中的不同Java对象

时间:2016-10-19 09:29:10

标签: java json gson

我有以下json字符串:

[
    {
        "question" : {
            "questionId" : 1109,
            "courseId" : 419
        },
        "tags" : ["PPAP", "testtest"],
        "choices" : [{
                "choiceId" : 0,
                "questionId" : 0
            }, {
                "choiceId" : 0,
                "questionId" : 0
            }
        ]
    }
]

如何使用GSON将问题,标签和选项分成单独的对象?目前我只使用fromJson并且只能转换JSON字符串,如果它只包含一种类型的对象。

2 个答案:

答案 0 :(得分:0)

您可以拥有以下课程

class Question{
   questionId; //specify data type 
   courseId;
}
class Choice{
   choiceId;
   questionId;
}

然后你可以再定义一个包含所有三个成员变量的类

class Extract{
 Question question;
 List<String> tags;
 List<Choice> choices;
} 

然后,您可以将此Extract类传递给fromJson方法,如

List<Extract> result = gson.fromJson(jsonString, new TypeToken<List<Extract>>(){}.getType());

答案 1 :(得分:0)

这适用于我定义的POJO类。

public static void main(String[] args) {
String jsonString = "[{\"question\":{\"questionId\":1109,\"courseId\":419},\"tags\":[\"PPAP\",\"testtest\"],\"choices\":[{\"choiceId\":0,\"questionId\":0},{\"choiceId\":0,\"questionId\":0}]}]";
        Gson gson = new Gson();

        JsonParser parser = new JsonParser();
        JsonArray array = parser.parse(jsonString).getAsJsonArray();

        for (final JsonElement json : array) {
            JsonModel jsonModel = gson.fromJson(json, new TypeToken<JsonModel>() {
            }.getType());
            System.out.println(jsonModel.toString());
        }

}
public class JsonModel implements Serializable {

    private static final long serialVersionUID = -2255013835370141266L;
    private List<Choices> choices;
    private List<String> tags;
    private Question question;
    ...    
    getters and setters
  }

public class Choices implements Serializable{

    private static final long serialVersionUID = 3947337014862847527L;

    private Integer choiceId;
    private Integer questionId;
    ...    
    getters and setters
}

public class Question implements Serializable{

    private static final long serialVersionUID = -8649775972572186614L;

    private Integer questionId;
    private Integer courseId;
    ...    
    getters and setters
}