http://xiangai.taobao.com
http://shop148612228.taobao.com

org.codehaus.jackson.map.JsonMappingException: Can not construct instance of java.util.Date from String value '20Spring Jackson 反序列化Date时遇到的问题

Jackson对于date的反序列化只支持几种,如果不符合默认格式则会报一下错误


org.codehaus.jackson.map.JsonMappingException: Can not construct instance of java.util.Date from String value '2012-12-12 12:01:01': not a valid representation (error: Can not parse date "2012-12-12 12:01:01": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
  at [Source: org.glassfish.jersey.message.internal.EntityInputStream@2c384e19; line: 1, column: 2] (through reference chain: jerseyspring.representation.Order["payTime"])
     at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
     at org.codehaus.jackson.map.deser.StdDeserializationContext.weirdStringException(StdDeserializationContext.java:243)
     at org.codehaus.jackson.map.deser.std.StdDeserializer._parseDate(StdDeserializer.java:577)
     at org.codehaus.jackson.map.deser.std.DateDeserializer.deserialize(DateDeserializer.java:28)
     at org.codehaus.jackson.map.deser.std.DateDeserializer.deserialize(DateDeserializer.java:19)
     at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:299)
     at org.codehaus.jackson.map.deser.SettableBeanProperty$MethodProperty.deserializeAndSet(SettableBeanProperty.java:414)
     at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:697)
     at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
     at org.codehaus.jackson.map.ObjectMapper._readValue(ObjectMapper.java:2704)
     at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1315)
     at org.codehaus.jackson.jaxrs.JacksonJsonProvider.readFrom(JacksonJsonProvider.java:419)



解决方案:

public class CustomJsonDateDeserializer extends JsonDeserializer<Date> {

    @Override
     public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                 String date = jp.getText();
                 try {
                     return format.parse(date);
                 } catch (ParseException e) {
                     throw new RuntimeException(e);
                 }
     }

}



且在字段的setter上加上注解

@JsonDeserialize(using = CustomJsonDateDeserializer.class)

posted @ 2018-02-07 21:48  万事俱备就差个程序员  阅读(1418)  评论(0编辑  收藏  举报

http://xiangai.taobao.com
http://shop148612228.taobao.com
如果您觉得对您有帮助.领个红包吧.谢谢.
支付宝红包
微信打赏 支付宝打赏