Saheb
Saheb

Reputation: 1492

Jackson accepting negative dates

I am trying to get a date field from JSON in a spring-boot application with Jackson. The JSONFormat looks like this:

@NotNull(message = ValidationErrors.NOT_BLANK_MESSAGE)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyyMMdd")
private Date date;

It works fine for most of the cases but when I pass 2017-0526, it is automatically converting it to 10th of May, 2018.

I want to throw exception in case the date is not in the yyyyMMdd format or contains minus sign. I tried going through stack overflow and Jackson documentation, but couldn't find anything.

Why is JsonFormat accepting negative dates?

Is there any workaround for this, so that it throws exception when such dates are passed?

Upvotes: 5

Views: 2255

Answers (2)

Isaace
Isaace

Reputation: 141

I wanted something that will affect the whole (spring-boot) project and came up with this:

@Configuration
public class JsonConfiguration {
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer customize() {
        return builder -> builder
                .dateFormat(StdDateFormat.instance.withLenient(false))
                .build();
    }
}

Upvotes: 0

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22234

This is an issue with the underlying Java class that parses dates. The parser is by default lenient and will parse dates that seem wrong. For stricter parsing you need to set the lenient property to false with the setLenient method. E.g. this setup will result in a InvalidFormatException when parsing a JSON with a date string "2017-0526":

ObjectMapper mapper = new ObjectMapper();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
df.setLenient(false);
mapper.setDateFormat(df);

At the moment you can't configure this through a @JsonFormat annotation. There seems to be a plan for that for version 2.9.0. Link to issue at github

Upvotes: 4

Related Questions