Home > Net >  How to disable ObjectMapper's invalid date conversion?
How to disable ObjectMapper's invalid date conversion?

Time:08-19

I have this fragment of code:

someValDto = objectMapper.readValue(
     payload, SomeClassDto.class
)

the payload is a string that contains a date. If a date is written like: 2000-13-01, it becomes 2001-01-01 in someValDto, is there a way to disable this in any way?

SomeClassDto has the following structure:

public class SomeClassDto {
    @XMLElement(name = "someDate")
    XMLGregorianCalendar someDate;
}

The configuration jackson class is:

@Configuration(proxyBeanMethods = false)
class JacksonObjectMapperConfig {
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
    builder.modules(new JaxbAnnotationModule(), new JavaTimeModule())
    .postConfigurer { it.setDefaultLeniency(false) }
    .defaultUseWrapper(false)
    .serizalitionInclusion(JsonInclude.Include.NON_NULL)
    .createXmlMapper(true)
    return builder;
    }
}

CodePudding user response:

You're looking for disabling of lenient date resolving, which allows the month in the ISO calendar system to be outside the range 1 to 12.

If you're using spring-boot, you can add a property to your application.yaml or application.properties file:

spring.jackson.default-leniency: false

But this property will be applied to the whole app. If you don't want to do this, try to configure a specific field in your SomeClassDto using Jackson annotation:

@JsonFormat(lenient = OptBoolean.FALSE)
private LocalDate date;

Note, that this property also applies to date-time format, i.e. if you have this property set to false and your date format is defined as yyyyMMdd you won't be able to parse a date like "yyyy-MM-dd" because of a strict mode.

CodePudding user response:

Use of LocalDate class introduced in java8 will be more stable in such cases.

Add the below maven dependency in your pom.xml

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.datatype/jackson-datatype-jsr310 -->
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.13.3</version>
</dependency>

and instantiate the ObjectMapper like below

ObjectMapper objectMapper = JsonMapper.builder().addModule(new JavaTimeModule()).build();

modify the datatype to LocalDate

@XMLElement(name = "someDate")
private LocalDate someDate;

This would throw some error in case of any invalid date is passed. Also make sure the date format is passed in the format : yyyy-MM-dd

  • Related