Spring MVC date serialization

Problem 1.

By default, Spring MVC serializes LocalData, LocalDataTime, and LocalTime into an ArrayList

Example 2.

The example Spring MVC serializes LocalData, LocalDataTime, and LocalTime

  • Serialized object

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
      class UserDto {
    
            private String userName;
            private LocalDateTime birthday;
    
       }
    Copy the code
  • The handler used to process requests

    The request passes in the UserDTO object, and the handler returns the serialized Json string of the UserDTO object, which shows what the birthday field of type LocalDateTime in the UserDTO is serialized for

    @RestController
    class HelloController {
    
         @PostMapping("/user")
         public UserDto user(@RequestBody UserDto userDto) throws Exception {
             returnuserDto; }}Copy the code
  • Send the request

  • Response content

    As you can see from the response,birthday is serialized as an array, proving that Spring MVC serializes LocalDateTime as an array by default

3. Solutions

  1. Use the @jsonFormat annotation

    • instructions

      You simply annotate the LocalDateTime field with @jsonFormat to declare the string format of the time

    • The sample

      Note That the string format sent during the request must be the same as that specified in the PATTERN declaration

      @Data
      @NoArgsConstructor
      @AllArgsConstructor
      class UserDto {
      
        private String userName;
        @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss")
        private LocalDateTime birthday;
          
      }
      Copy the code
    • The results of

      At this point, the way Spring MVC serializes the LocalDateTime type does change

  2. Custom serialization

    • instructions

      Jackson also provides a complete serialization scheme for this. We simply introduce the jackson-datatyp-JSR310 dependency in pem.xml, then add the serialization module to the application main class, and disable the timestamp output feature for dates

    • The sample

      • Maven introduces dependencies

        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
        </dependency
        Copy the code
      • Add serialization module

         @Bean
         public ObjectMapper serializingObjectMapper(a) {
             ObjectMapper objectMapper = new ObjectMapper();
             // Disallow serializing Date as a timestamp
             objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
             objectMapper.registerModule(new JavaTimeModule());// Register module
             return objectMapper;
         }
        Copy the code
    • The results show

      The string format must be in the format of YYYY-MM-DDTHh: MM :ss.

      For example, “2022-02-22T22:22:22”, in order to receive the request parameters normal conversion

      • request

        The request is a birthday string in the format YYYY-MM-DDTHh: MM: SS

      • The response

        Now that the JavaTimeModule serialization module is registered, the way Spring MVC serializes the LocalDateTime type does change

4. To summarize

Spring MVC will default LocalDate LocalDateTime, LocalTime serialized as an array, in some scenarios will go wrong, so need to modify the default serialization of the Spring MVC, serialization results from an array into a time string.

The above example only uses LocalDateTime, but for LocalDate,LocalTime is universal.

Refer to the article: blog.didispace.com/Spring-Boot…