我有一个JSON响应,我想使用GSON反序列化。 JSON结构使用日期字符串作为属性名称。如何将这种反序列化。
{
2015-04-23: [{
seqNum: 1,
distance: 13,
start: "123 Main St"
end: "225 Broadway"
},
{seqNum: 2
distance: 21,
start: "225 Broadway"
end: "12 West St"
}
]
}
答案 0 :(得分:1)
在我的回答中,我认为你可以有这样的JSON响应:
{
"2015-04-23": [
{
"seqNum": 1,
"distance": 13,
"start": "123 Main St",
"end": "225 Broadway"
},
{
"seqNum": 2,
"distance": 21,
"start": "225 Broadway",
"end": "12 West St"
}
],
"2015-04-24": [
{
"seqNum": 1,
"distance": 13,
"start": "123 Main St",
"end": "225 Broadway"
},
{
"seqNum": 2,
"distance": 21,
"start": "225 Broadway",
"end": "12 West St"
}
]
}
所以第一步是创建适当的类。
class MyObject {
private List<DateMapping> dateMappings;
public MyObject(List<DateMapping> dateMappings) {
this.dateMappings = dateMappings;
}
...
}
class DateMapping {
private Date date;
private List<Sequence> sequences;
public DateMapping(Date date, List<Sequence> sequences) {
this.date = date;
this.sequences = sequences;
}
...
}
class Sequence {
private int seqNum;
private int distance;
private String start;
private String end;
...
}
现在你如何解析密钥,因为它们是动态的?答案是使用自定义反序列化器:
class MyObjectAdapter implements JsonDeserializer<MyObject> {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
private static final Type listSequenceType = new TypeToken<List<Sequence>>(){}.getType();
public MyObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
List<DateMapping> dateMappings = new ArrayList<>();
for(Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
try {
dateMappings.add(new DateMapping(dateFormat.parse(entry.getKey()), context.deserialize(entry.getValue(), listSequenceType)));
} catch (ParseException e) {
e.printStackTrace();
throw new RuntimeException("Can't parse the date");
}
}
return new MyObject(dateMappings);
}
}
从那里你可以看到我迭代顶层JsonObject
的每个条目,从中为每个条目创建一个新的DateMapping
。然后你只需要在Gson解析器中注册适配器就可以了。
Gson gson = new GsonBuilder().registerTypeAdapter(MyObject.class, new MyObjectAdapter()).create();
MyObject myObject = gson.fromJson(new FileReader(new File("myJson")), MyObject.class);
在上面的示例上运行会产生输出:
MyObject =>
DateMapping Thu Apr 23 00:00:00 CEST 2015, sequences=[Sequence{seqNum=1, distance=13, start='123 Main St', end='225 Broadway'}, Sequence{seqNum=2, distance=21, start='225 Broadway', end='12 West St'}]
DateMapping Fri Apr 24 00:00:00 CEST 2015, sequences=[Sequence{seqNum=1, distance=13, start='123 Main St', end='225 Broadway'}, Sequence{seqNum=2, distance=21, start='225 Broadway', end='12 West St'}]
如果您只有一个条目,则可以跳过创建类MyObject
,并获取JsonObject
的第一个条目,您可以从中创建单个DateMapping
实例。
希望它有所帮助! :)