Spring Jackson 反序列化Date时遇到的问题(http://www.aichengxu.com/java/81030.htm)

Spring 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)

你可能感兴趣的:(Spring Jackson 反序列化Date时遇到的问题(http://www.aichengxu.com/java/81030.htm))