How to set format of string for java.time.Instant using objectMapper?

后端 未结 7 852
失恋的感觉
失恋的感觉 2020-11-29 04:37

I have an entity with java.time.Instant for created data field:

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public         


        
7条回答
  •  清酒与你
    2020-11-29 05:14

    For those looking to parse Java 8 timestamps. 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);
    }
    

提交回复
热议问题