问题
I have the following json string:
[
{
"question" : {
"questionId" : 1109,
"courseId" : 419
},
"tags" : ["PPAP", "testtest"],
"choices" : [{
"choiceId" : 0,
"questionId" : 0
}, {
"choiceId" : 0,
"questionId" : 0
}
]
}
]
How do I make question, tags, and choices into separate objects using GSON? Currently I only use fromJson and can only convert a JSON string if it only contains 1 type of object.
回答1:
You can have following classes
class Question{
questionId; //specify data type
courseId;
}
class Choice{
choiceId;
questionId;
}
Then you can define one more class which will hold all the three member variables
class Extract{
Question question;
List<String> tags;
List<Choice> choices;
}
Then you can pass this Extract class to fromJson method like
List<Extract> result = gson.fromJson(jsonString, new TypeToken<List<Extract>>(){}.getType());
回答2:
This worked for me with the POJO classes defined.
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
}
来源:https://stackoverflow.com/questions/40127403/converting-json-list-as-different-java-objects-in-gson