Jackson serializes a ZonedDateTime wrongly in Spring Boot

前端 未结 4 1847
有刺的猬
有刺的猬 2021-02-05 01:28

I have a simple application with Spring Boot and Jetty. I have a simple controller returning an object which has a Java 8 ZonedDateTime:

public clas         


        
4条回答
  •  别跟我提以往
    2021-02-05 02:20

    The answer was already mentioned above but I think it's missing some info. For those looking to parse Java 8 timestamps in many forms (not just ZonedDateTime). You need a recent version of jackson-datatype-jsr310 in your POM and have the following module registered:

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new JavaTimeModule());
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    

    To test this code

    @Test
    void testSeliarization() throws IOException {
        String expectedJson = "{\"parseDate\":\"2018-12-04T18:47:38.927Z\"}";
        MyPojo pojo = new MyPojo(ZonedDateTime.parse("2018-12-04T18:47:38.927Z"));
    
        // serialization
        assertThat(objectMapper.writeValueAsString(pojo)).isEqualTo(expectedJson);
    
        // deserialization
        assertThat(objectMapper.readValue(expectedJson, MyPojo.class)).isEqualTo(pojo);
    }
    

    Note that you can configure your object mapper globally in Spring or dropwizard to achieve this. I have not yet found a clean way to do this as an annotation on a field without registering a custom (de)serializer.

提交回复
热议问题