Jackson date deserialization - “invalid” day of month

此生再无相见时 提交于 2021-01-28 12:20:21

问题


I am using Spring Boot with Jackson serializing/deserializing JSON requests/responses. I have come accross a behaviour when trying to deserialize Date in ISO format that I would like to avoid.

When I use an invalid day of month or month of year, Jackson handles it by adding the extra number of days/months to the date.

For instance

{
    "date": "2018-02-40T15:00:00+01:00"
}

is deserialized as Mon Mar 12 15:00:00 CET 2018

Or

{
    "date": "2018-14-20T15:00:00+01:00"
}

as Wed Feb 20 15:00:00 CET 2019

Is there a way to enforce a validation somehow? I was looking at the list of Serialization and Deserialization features but I was not able to find any that could influence this behaviour.

I am using the old Java Date API - java.util.Date.


回答1:


Your answers pointed me the right direction. Jackson supports leniency configuration using the @JsonFormat annotation since 2.9+.

@JsonFormat(lenient = OptBoolean.FALSE)

So all I had to do was to override the value of the jackson.version property in POM as I am using the Spring Boot parent POM.

<jackson.version>2.9.4</jackson.version>

Thanks again!




回答2:


Since you're using the old API, turn on strict mode by calling setLenient(false) on the Calendar associated with the DateFormat you're using.




回答3:


SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss+01:00"); 
sdf.setLenient(false);
objectMapper.setDateFormat(sdf);

A similar question: Jackson ObjectMapper : Issues with date serialization and deserialization




回答4:


As you mentioned you using spring-boot,
You can create a configuration to your ObjectMapper

@Configuration
public class ObjectMapperConfig {
    @Bean
    public ObjectMapper objectMapper(){
        ObjectMapper mapper = new ObjectMapper();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss+01:00");
        simpleDateFormat.setLenient(false);
        mapper.setDateFormat(simpleDateFormat);

        return mapper;
    }
}

And then everytime you want yo use just inject your ObjectMapper

@Autowired
private ObjectMapper mapper;


来源:https://stackoverflow.com/questions/48934700/jackson-date-deserialization-invalid-day-of-month

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!