How to parse nested JSON with GSON

ぃ、小莉子 提交于 2020-01-04 06:03:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!