Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure Jackson instead using DateTimeFormat.ISO.DATE - not working

Tags:

I want to configure Jackson instead using DateTimeFormat.ISO.DATE every time when I'm requesting a date for example:

@RequestMapping(value = "income")
  public ResponseEntity calculateIncome(
      @RequestParam(value = "companyName") String companyName,
      @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
      @RequestParam(value = "startDate") LocalDate startDate,
      @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
      @RequestParam(value = "endDate") LocalDate endDate
  ) 

I've already tried setup it in JacksonConfig

mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

or

mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

also

mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

or

mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);

even in application.properties i tried

spring.jackson.serialization.write_dates_as_timestamps=true

I'm using spring-boot wit following dependencies

 <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
      <version>1.5.10.RELEASE</version>
    </dependency>
<dependency>
      <groupId>com.fasterxml.jackson.datatype</groupId>
      <artifactId>jackson-datatype-jsr310</artifactId>
      <version>${jackson.version}</version>
    </dependency>

I just don't want to repeat over and over the same @DataTimeFormat but without it, I'm still getting error:

in IntelJ

2018-03-01 15:35:05.539 WARN 8168 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to bind request element: org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam java.time.LocalDate] for value '2018-02-28'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2018-02-28]

Postman

{
    "timestamp": 1519914905555,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.method.annotation.MethodArgumentTypeMismatchException",
    "message": "Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam java.time.LocalDate] for value '2018-02-28'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2018-02-28]",
    "path": "/incVat"
}

or

{
    "timestamp": "2018-03-01T15:36:44.823+0000",
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.method.annotation.MethodArgumentTypeMismatchException",
    "message": "Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam java.time.LocalDate] for value '2018-02-28'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2018-02-28]",
    "path": "/incVat"
}
like image 941
lukaszgo3 Avatar asked Mar 01 '18 15:03

lukaszgo3


People also ask

How does Jackson serialize date?

It's important to note that Jackson will serialize the Date to a timestamp format by default (number of milliseconds since January 1st, 1970, UTC).

How does Jackson deserialize dates from JSON?

This is how i'm deserializing the date: SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); getObjectMapper(). getDeserializationConfig(). setDateFormat(dateFormat);

How do I change the date format in object mapper?

We can format a date using the setDateFormat() of ObjectMapper class. This method can be used for configuring the default DateFormat when serializing time values as Strings and deserializing from JSON Strings.


2 Answers

SOLUTION: I Have found the solution here It's all about a custom editor for LocalDate and implementation of Formatter

@Bean
  public Formatter<LocalDate> localDateFormatter() {
    return new Formatter<LocalDate>() {
      @Override
      public LocalDate parse(String text, Locale locale) throws ParseException {
        return LocalDate.parse(text, DateTimeFormatter.ISO_DATE);
      }

      @Override
      public String print(LocalDate object, Locale locale) {
        return DateTimeFormatter.ISO_DATE.format(object);
      }
    };
  }
like image 124
lukaszgo3 Avatar answered Nov 15 '22 05:11

lukaszgo3


You need this in your pom.xml:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

And in your Configuration class:

@Configuration
public class WebConfigurer {

    @Bean
    @Primary // pay attention on this
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.build();
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        return objectMapper;
    }
}

And the Jackson2Json configuration:

@Configuration
public class Jackson2JsonConfiguration {
    @Bean
    public Jackson2JsonObjectMapper jackson2JsonObjectMapper(ObjectMapper objectMapper) {
        return new Jackson2JsonObjectMapper(objectMapper);
    }
}

If not work, try:

  • to change the order of the import of jsr310 dependency in the pom.xml.
  • add in the properties file: jackson.serialization.write-dates-as-timestamps = false

I had weird problems trying to make this work too.

As a last option, you could migrate to Spring Boot 2.0, because they flipped the Jackson configuration default to write JSR-310 dates as ISO-8601 strings.

like image 23
Dherik Avatar answered Nov 15 '22 03:11

Dherik