我如何使杰克逊反序列化一个长日期对象? [英] How can I make Jackson deserialize a Long to a Date Object?

查看:174
本文介绍了我如何使杰克逊反序列化一个长日期对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在序列化Map中的一些java.util.Dates。日期序列化为Longs(Jackson将 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆