MaikelS
MaikelS

Reputation: 1299

How to parse nested JSON with GSON

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());

Upvotes: 2

Views: 2861

Answers (2)

Zephyr
Zephyr

Reputation: 6351

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.

Upvotes: 0

curioustechizen
curioustechizen

Reputation: 10672

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);

Upvotes: 4

Related Questions