GSON解析动态JSON字段 [英] GSON parsing dynamic JSON field
问题描述
我不确定是否需要注册一个新的TypeToken或什么。但我的JSON对象如下所示:
{
id:6,
error :0,
dates:{
34234:2011-01-01//我想将日期解析为一个字符串。
87474:2011-08-09//第一个值都是唯一的。
。 //这可以是任意数量的条目。
。
。
74857:2011-09-22
}
}
我创建了这样的两个对象:
public class Response {
public整数ID;
public String error;
public DateList日期;
$ p
pre> public class DateList {
public List< Map< Integer,String>> dateString;
}
我不确定如何调整它以使其正确。文档似乎没有帮助...而我见过的其他例子是解析自定义对象,而不是字符串类型。
谢谢!
我尝试过这种形式:
The Json
{
id:6,
错误:0,
日期: {
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>日期;
}
至少这似乎是开箱即用的。
I can't seem to figure this out. I've looked at a couple SO posts (here, and here), and my situation is just a little different.
I'm not sure if I have to register a new TypeToken or what. But my JSON object looks like this:
{
"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"
}
}
I've created both of my objects like this:
public class Response {
public Integer id;
public String error;
public DateList dates;
}
Separate file:
public class DateList {
public List<Map<Integer, String>> dateString;
}
I'm not sure how to tweek it to get it right. Documentation doesn't seem to help... And the other examples I've seen are parsing a custom object, not a string type.
Thanks!
I tried it in this form:
The Json
{
"id": 6,
"error": "0",
"dates": {
"34234" : "2011-01-01"
"87474" : "2011-08-09"
"74857" : "2011-09-22"
}
}
And the Response.java
public class Response {
public Integer id;
public String error;
public Map<Integer, String> dates;
}
At least that seemed to work out of the box.
这篇关于GSON解析动态JSON字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!