Parsing JSON with GSON

大城市里の小女人 提交于 2020-01-12 23:13:12

问题


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:


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.



来源:https://stackoverflow.com/questions/2710137/parsing-json-with-gson

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