问题
Lets say i have a JSON like:
{
"assignments": [
{
'id': '111',
'activities': [
{
'activity': 'Activity 1',
},
{
'activity': 'Activity 2'
}
]
},
{
'id': '2222',
'Activities': [
{
'activity': 'Activity 1'
}
]
}
]
}
And I'm using GSON to parse it. I have a correctly set up Javabean and can access id without problems. How do i get the activities per id / object?
EDIT: more code:
public class Assignment {
private String id;
public String getId() {
return id;
}
}
Gson mGson= new Gson();
assignmentList=mGson.fromJson(json, AssignmentList.class);
assignmentList.getAssignments().get(0).getId());
回答1:
I'd create another Bean for Activities since it is a JSON object in itself.
class Assignment {
private String id;
private List<Activity> activities; //getters and setters for this.
public String getId() {
return id;
}
}
class Activity {
private String activity; //Getters and setters
}
Gson mGson= new Gson();
assignmentList=mGson.fromJson(json, AssignmentList.class);
assignmentList.getAssignments().get(0).getActivities.get(1);
回答2:
If there are only primitive types in the class, just defining two Java classes should be enough, just make sure not to inherit the class from GenericJson, it breaks the recursive operation of a Gson parser.
来源:https://stackoverflow.com/questions/8679328/how-to-parse-nested-json-with-gson