2013-02-25 80 views
3

我使用Spring框架从GET请求接收JSON。一切工作好了,等到错误的值放入数据库,并发生这种情况:忽略杰克逊中的无效值,使用弹簧

02-25 14:46:04.035: E/AndroidRuntime(12271): org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not construct instance of java.util.Date from String value '-3600': not a valid representation (error: Failed to parse Date value '-3600': Can not parse date "-3600": 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"))

我如何设置杰克逊忽略无法读取/ parseble值?我宁愿没有或多于我的完整json解析失败...

这里是我的对象,我试图解析,因为你可以看到我试图忽略jsonignoreproperties属性在我的代码中的属性。

收据:

public class Receipt { 

    public String categories; 


    @JsonProperty("expiration_date") 
    public Date expirationDate; 

    public String image1; 

    public String image2; 
(.. more properties, getters and setters ..) 

,我怎么尝试解析:

RestTemplate restTemplate = new RestTemplate(); 


    // instellen dat de converter ongedefineerde parameters negeert 
    HttpMessageConverter customconver = new MappingJackson2HttpMessageConverter(); 
    ((MappingJackson2HttpMessageConverter) customconver).getObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); //here the ignore unknown 

    restTemplate.getMessageConverters().add(customconver); 
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter()); 
    try { 
    // GET Request 
    ResponseEntity<ReceiptMessage> response = restTemplate.exchange(urlPath, HttpMethod.GET,requestEntity,ReceiptMessage.class); 

记住,前值-3600解析器我工作得很好,所以没有问题。

有没有办法忽略这类错误?

回答

0

ObjectMapper上有一个名为WRITE_DATES_AS_TIMESTAMPS的设置。这会导致日期序列化为longs而不是字符串,因此禁用它以获取字符串。你绝对应该读这个:http://wiki.fasterxml.com/JacksonFAQDateHandling

如果你不想这样做,要忽略一个基于某种逻辑的字段,只需添加一个setter为日期字段,需要很长时间并自己解析它。你可能需要用@JsonSetter("expiration_date")注释它,所以杰克逊知道在那里传递它。

最后,Java日期/日历API通常被认为是完全可怕的,应尽可能避免每种情况。如果您使用的是Java 8,则新的日期/时间apis要好得多。如果您在Java 8之前,请使用JodaTime。甚至还有一个特殊的杰克逊模块来处理它。