我怎样才能让杰克逊反序列化一个长期的日期对象?
我正在映射中序列化一些 java.util.Dates 。日期被序列化为 Long(Jackson 将 Date
实例的 Long
值写入 JSON 字符串),但是,它们不会被反序列化回 Date
实例,但作为 Long
实例。
我希望 Jackson 将日期反序列化回 Date 对象(而不是格式化字符串或长整型),我怎样才能实现这一点?
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
生产
{"DESCRIPTION":"LIBOR"},{"RATE":"1.8"},{"DATE":1246402800000}, ... }
什么都可以。但是,当我希望日期字符串成为 java.util.Date
的实例时,它会被反序列化(膨胀)回 java.lang.Long
的实例 -这就是它开始的样子。 即地图更改
现在包含三个条目;描述为 String
,速率为 Float
,日期为 Long
。
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
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您想要使用 org.codehaus.jackson.map.JsonDeserializer 并编写自定义反序列化代码。类似于:
我想您必须弄清楚何时必须将 Long 属性反序列化为 Date。也许在你的 pojo 上使用注释?
You want to use org.codehaus.jackson.map.JsonDeserializer and write the custom deserialization code. Something like:
I guess you have to figure out when a Long property has to be deserialized to Date. Maybe using annotations on your pojos?
我不知道日期的字符串表示是否有帮助?
如果是,那么您可以尝试在 ObjectMapper 上设置 DateFormat。然后反序列化将采用可读的字符串格式。
例如,对于下面的代码,输出将类似于 [{"birthDate":"March 30, 2011"}]
I don't know if a String representation of the Date would be of any help?
If yes, then you could try setting the DateFormat on the ObjectMapper. The deserialization would then be in the readable String format.
E.g for the below code, the output would be like [{"birthDate":"March 30, 2011"}]