jackson的學習記錄

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)
解決方案
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)
	
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章