GSON将键值反序列化为自定义对象 [英] GSON deserializing key-value to custom object
问题描述
我需要反序列化json,它是一个包含日期/长整型值的数组。以下是返回的JSON示例:
[{2011-04-30T00:00:00-07:00 :100},{2011-04-29T00:00:00-07:00:200}]
使用GSON我可以将它反序列化为 List< Map< Date,String>>
,但希望能够将它转换为 List< MyCustomClass>
类似于:
public class MyCustomClass(){
日期日期;
长期价值;
}
我似乎无法找到指示GSON映射键/值的方法JSON映射到我的自定义类中的日期/值字段。有没有办法做到这一点,或者是地图列表的唯一路线?
你需要编写一个自定义的解串器。您还需要使用时区格式 SimpleDateFormat
实际上可以解析。 z
和 Z
都不会匹配 -07:00
,这是一种奇怪的RFC 822时区格式( -0700
)或一般时区( Mountain Standard Time
或 MST
或 GMT-07:00
)。或者,您可以使用完全相同的时区格式,并且使用JodaTime的 DateTimeFormat
。 $ b
MyCustomClass.java
public class MyCustomClass
{
日期日期;
长期价值;
public MyCustomClass(日期日期,长整型值)
{
this.date = date;
this.value = value;
}
@Override
public String toString()
{
return{date:+ date +,value:+ value + };
$ / code $ / pre
$ b MyCustomDeserializer.java
public class MyCustomDeserializer实现了JsonDeserializer< MyCustomClass>
{
private DateFormat df = new SimpleDateFormat(yyyy-MM-dd'T'HH:mm:ssz);
@Override
public MyCustomClass deserialize(JsonElement json,Type typeOfT,JsonDeserializationContext ctx)throws JsonParseException
{
JsonObject obj = json.getAsJsonObject();
条目< String,JsonElement> entry = obj.entrySet()。iterator()。next();
if(entry == null)return null;
日期日期;
尝试
{
date = df.parse(entry.getKey());
}
catch(ParseException e)
{
e.printStackTrace();
date = null;
}
Long value = entry.getValue()。getAsLong();
返回新的MyCustomClass(日期,值);
$ b GsonTest.java
public class GsonTest
{
public static void main(String [] args)
{
//注意时区格式调整(删除':')
String json =[{\2011-04-30T00:00:00-0700 \:100},{\2011-04-04 -29T00:00:00-0700\ :200}];
Gson gson =
new GsonBuilder()
.registerTypeAdapter(MyCustomClass.class,new MyCustomDeserializer())
.create();
Type collectionType = new TypeToken< Collection< MyCustomClass>>(){}。getType();
收藏< MyCustomClass> myCustomClasses = gson.fromJson(json,collectionType);
System.out.println(myCustomClasses);
以上所有代码都是 on Github ,随时克隆(尽管你会得到代码也回答其他问题)。
I need to deserialize json which is an array of date/long values. Here is an example of the returned JSON:
[{"2011-04-30T00:00:00-07:00":100}, {"2011-04-29T00:00:00-07:00":200}]
Using GSON I am able to deserialize this to a List<Map<Date,String>>
, but would like to be able to convert it to a List<MyCustomClass>
similar to:
public class MyCustomClass() {
Date date;
Long value;
}
I cannot seem to find a way to instruct GSON to map the key/value of the JSON map to the date/value fields in my custom class. Is there a way to do this, or is a list of maps the only route?
解决方案 You need to write a custom deserializer. You also need to use a time zone format that SimpleDateFormat
can actually parse. Neither z
nor Z
will match -07:00
, which is a weird mix of RFC 822 time zone format (-0700
) or a "general time zone" (Mountain Standard Time
or MST
or GMT-07:00
). Alternately, you can stick with the exact same time zone format, and use JodaTime's DateTimeFormat
.
MyCustomClass.java
public class MyCustomClass
{
Date date;
Long value;
public MyCustomClass (Date date, Long value)
{
this.date = date;
this.value = value;
}
@Override
public String toString()
{
return "{date: " + date + ", value: " + value + "}";
}
}
MyCustomDeserializer.java
public class MyCustomDeserializer implements JsonDeserializer<MyCustomClass>
{
private DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
@Override
public MyCustomClass deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) throws JsonParseException
{
JsonObject obj = json.getAsJsonObject();
Entry<String, JsonElement> entry = obj.entrySet().iterator().next();
if (entry == null) return null;
Date date;
try
{
date = df.parse(entry.getKey());
}
catch (ParseException e)
{
e.printStackTrace();
date = null;
}
Long value = entry.getValue().getAsLong();
return new MyCustomClass(date, value);
}
}
GsonTest.java
public class GsonTest
{
public static void main(String[] args)
{
// Note the time zone format tweak (removed the ':')
String json = "[{\"2011-04-30T00:00:00-0700\":100}, {\"2011-04-29T00:00:00-0700\":200}]";
Gson gson =
new GsonBuilder()
.registerTypeAdapter(MyCustomClass.class, new MyCustomDeserializer())
.create();
Type collectionType = new TypeToken<Collection<MyCustomClass>>(){}.getType();
Collection<MyCustomClass> myCustomClasses = gson.fromJson(json, collectionType);
System.out.println(myCustomClasses);
}
}
All of the above code is on Github, feel free to clone (though you'll get code for answers to other questions as well).
这篇关于GSON将键值反序列化为自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!