在Android中使用GSON解析一个复杂的JSON对象复杂、对象、Android、GSON

2023-09-04 03:07:49 作者:谁守她城ゅ ˉ7c

我是比较新的Java编程和需要解析跨线复杂的JSON对象。我一直在阅读上GSON文档过去一天,还没有多少运气能够完全分析这种类型的结构:

I'm relatively new to Java programming and need to parse a complex JSON object across the wire. I've been reading documentation on GSON the past day and Haven't had much luck being able to fully parse this type of structure:

{
  'Events' : [{
    'name' : 'exp',
    'date' : '10-10-2010',
    'tags' : ["tag 1", "tag2", "tag3"]
    },...more events...],
  'Contacts' : [{
    'name' : 'John Smith',
    'date' : '10-10-2010',
    'tags' : ["tag 1", "tag2", "tag3"]
    },...more contacts...],
}

我已经能够得到它的工作类似于这个的问题,但无法弄清楚如何获得附加阵列级的工作。

I've been able to get it to work similarly to this question but can't figure out how to get that additional array level to work.

推荐答案

在我找的格式使用GSON做正确的方法是:

The correct way to do it using GSON in the format I'm looking for is:

//somewhere after the web response:
Gson gson = new Gson();

Event[] events = gson.fromJson(webServiceResponse,  Event[].class);


//somewhere nested in the class:
static class Event{
    String name;
    String date;

    public String getName()
    {
        return name;
    }

    public String getDate()
    {
        return date;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public void setDate(String date)
    {
        this.date = date;
    }
}