本文介绍了JSON解析与GSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用GSON一些麻烦,主要是从JSON反序列化到一个POJO。

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

我有以下的JSON:

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

通过下面的POJO的...

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

......,我反序列化具有以下code,其中JSON输入高于

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

不过,我不能让事件列表中正确填充。标题和ID总是空。我敢肯定,我失去了一些东西,但我不知道是什么。任何想法?

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?

感谢

推荐答案

OK,我想通了这一点。我证明这编码一个漫长的一天,很少睡眠的前一天晚上!

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

该事件数据结构包含多个事件,其中每个包含一个事件类型。我不得不将EventSearchEvent下一个新类EventContainer。此事件容器中包含一个字段事件。这个事件是EventSearchEvent。因此,当GSON遍历JSON数组,它看到的容器(这是类型为事件),然后里面的那个对象就找了一个事件成员。当它终于发现它装起来的ID和标题恰当。

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.

这篇关于JSON解析与GSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 18:05