tags:

views:

482

answers:

1

I'm having some trouble with GSON, mainly deserializing from JSON to a POJO.

I have the following JSON:

{
    "events": 
    [
        {
            "event": 
            {
                "id": 628374485, 
                "title": "Developing for the Windows Phone"
            }
        },
        {
            "event": 
            {
                "id": 765432, 
                "title": "Film Makers Meeting"
            }
        }
    ]
}

With the following POJO's ...

public class EventSearchResult {

    private List<EventSearchEvent> events; 

    public List<EventSearchEvent> getEvents() {
        return events;
    }

}
public class EventSearchEvent {

    private int id; 
    private String title;


    public int getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }
}

... and I'm deserializing with the following code, where json input is the json above

Gson gson = new Gson();
return gson.fromJson(jsonInput, EventSearchResult.class);   

However, I cannot get the list of events to populate correctly. The title and id are always null. I'm sure I'm missing something, but I'm not sure what. Any idea?

Thanks

+1  A: 

OK, I figured this out. I attest this to a long day of coding with little sleep the night before!

The "events" data structure contained multiple "events", which each contain an "event" type. I had to move the EventSearchEvent under a new class called EventContainer. This event container contained one field "event". This "event" was the "EventSearchEvent". THerefore, when GSON iterated over the JSON array, it saw the Container (which is of type "events") and then inside of that object it looked for a "event" member. When it finally found that it loaded up the id and title appropriately.

The short of it: I didn't have my object hierarchy built correctly.

Donn Felker