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-

时间:2024-04-23 12:36:06

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)

解决方案:

import java.io.IOException;

import java.text.*;

import java.util.Date;

import com.fasterxml.jackson.core.*;

import com.fasterxml.jackson.databind.*;

import com.fasterxml.jackson.databind.*;

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)