【问题标题】:Parsing JSON with GSON使用 GSON 解析 JSON
【发布时间】:2011-02-12 04:48:27
【问题描述】:

我在使用 GSON 时遇到了一些问题,主要是从 JSON 反序列化到 POJO。

我有以下 JSON:

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

使用以下 POJO 的 ...

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

...我正在使用以下代码进行反序列化,其中 json 输入是上面的 json

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

但是,我无法正确填充事件列表。标题和 ID 始终为空。我确定我错过了一些东西,但我不确定是什么。任何想法?

谢谢

【问题讨论】:

    标签: android json gson


    【解决方案1】:

    好的,我想通了。我证明了这一点,前一天晚上几乎没有睡觉的一整天编码!

    “事件”数据结构包含多个“事件”,每个事件都包含一个“事件”类型。我不得不将 EventSearchEvent 移到一个名为 EventContainer 的新类下。此事件容器包含一个字段“事件”。这个“事件”就是“EventSearchEvent”。因此,当 GSON 遍历 JSON 数组时,它看到了容器(属于“事件”类型),然后在该对象内部寻找“事件”成员。当它最终发现它正确地加载了 id 和 title 时。

    简而言之:我没有正确构建对象层次结构。

    【讨论】:

    猜你喜欢
    • 2012-01-02
    • 1970-01-01
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多