2011-10-04 89 views
6

我似乎无法弄清楚这一点。我看过一些SO帖子(herehere),我的情况有点不同。GSON解析动态JSON字段

我不确定是否需要注册一个新的TypeToken或什么。但我的JSON对象是这样的:

{ 
    "id": 6, 
    "error": "0", 
    "dates": { 
     34234 : "2011-01-01" // I want to parse the date into a string. 
     87474 : "2011-08-09" // The first values are all unique. 
     .     //this can be any number of entries. 
     . 
     . 
     74857 : "2011-09-22" 
    } 
} 

我已经创建了我的两个对象是这样的:

public class Response { 

    public Integer id; 
    public String error; 
    public DateList dates; 
} 

独立文件:

public class DateList { 

    public List<Map<Integer, String>> dateString; 
} 

我不知道如何驯服它是为了让它正确。文档似乎没有帮助...而我见过的其他例子是解析一个自定义对象,而不是字符串类型。

谢谢!

+2

我不知道GSON是什么,但是'List '至少缺少一个'>'。另外,它不应该只是一张地图而不是一张地图清单? – svens

+0

对不起,我没有复制并粘贴该代码。谢谢您的帮助! –

回答

12

我尝试以这种形式:

JSON的

{ 
    "id": 6, 
    "error": "0", 
    "dates": { 
     "34234" : "2011-01-01" 
     "87474" : "2011-08-09" 
     "74857" : "2011-09-22" 
    } 
} 

而且Response.java

public class Response { 
    public Integer id; 
    public String error; 
    public Map<Integer, String> dates; 
} 

至少,这似乎工作开箱。

+0

谢谢!我知道这很简单! –

+0

也为我工作。我以为我必须写一个自定义的TypeAdapter或神奇的东西。 – squeeish