我如何使杰克逊反序列化一个长日期对象? [英] How can I make Jackson deserialize a Long to a Date Object?
问题描述
Date
实例的 Long
值写入JSON字符串),但是,它们没有被反序列化为 Date
实例,而是作为 Long
实例。 我希望杰克逊将日期重新排序为Date对象(而不是格式化的String或Longs),我该如何实现? b
$ b
Map< String,Comparable<?>> change = new HashMap< String,Comparable<?>>();
change.put(DESCRIPTION,LIBOR);
change.put(RATE,1.8);
change.put(DATE,Util.newDate(2009,7,1)); //返回一个java.util.Date
生成
{DESCRIPTION:LIBOR},{RATE:1.8},{DATE:1246402800000},...}
哪个是好的但是,日期字符串被反序列化(膨胀)回到 java.lang.Long
的实例,当我想要它是一个 java的实例.util.Date
- 这是它开始的。
即地图更改
现在包含三个条目;描述为 String
,作为浮动
和日期作为长
。
您要使用org.codehaus.jackson.map.JsonDeserializer并编写自定义反序列化代码。如下所示:
public class DateDeserializer extends JsonDeserializer< Long> {
@Override
public Long deserialize(JsonParser jp,DeserializationContext ctxt)throws IOException,JsonProcessingException {
...自定义逻辑
}
}
我想你必须弄清楚Long属性何时被反序列化为Date。也许在你的pojos上使用注释?
I'm serializing some java.util.Dates within a Map. The dates are serialized into Longs (Jackson writes the Long
value of the Date
instance to the JSON string), however, they're not being de-serialized back to Date
instances, but as Long
instances.
I'd like Jackson to de-serialize the dates back to Date objects (rather than formatted Strings or Longs), how can I achieve this?
Map<String, Comparable<?>> change = new HashMap<String, Comparable<?>>();
change.put("DESCRIPTION", "LIBOR");
change.put("RATE", "1.8");
change.put("DATE", Util.newDate(2009, 7, 1)); // Returns a java.util.Date
Produces
{"DESCRIPTION":"LIBOR"},{"RATE":"1.8"},{"DATE":1246402800000}, ... }
Which is okay. However, the date String is deserialized (inflated) back into an instance of java.lang.Long
, when I want it to be an instance of java.util.Date
- which is what it started as.
i.e. Map change
now contains three entries; Description as a String
, Rate as a Float
and Date as a Long
.
You want to use org.codehaus.jackson.map.JsonDeserializer and write the custom deserialization code. Something like:
public class DateDeserializer extends JsonDeserializer<Long> {
@Override
public Long deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
... custom logic
}
}
I guess you have to figure out when a Long property has to be deserialized to Date. Maybe using annotations on your pojos?
这篇关于我如何使杰克逊反序列化一个长日期对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!