5

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 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I have a similar issue on this question here stackoverflow.com/questions/9799549/… Look at my last comment in the answer by LouieLouie.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.