Java 8 LocalDate Jackson format

前端 未结 14 1178
傲寒
傲寒 2020-11-22 12:59

For java.util.Date when I do

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = \"dd/MM/yyyy\")  
  private Date dateOfBirth;
<         


        
14条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 13:54

    https://stackoverflow.com/a/53251526/1282532 is the simplest way to serialize/deserialize property. I have two concerns regarding this approach - up to some point violation of DRY principle and high coupling between pojo and mapper.

    public class Trade {
        @JsonFormat(pattern = "yyyyMMdd")
        @JsonDeserialize(using = LocalDateDeserializer.class)
        @JsonSerialize(using = LocalDateSerializer.class)
        private LocalDate tradeDate;
        @JsonFormat(pattern = "yyyyMMdd")
        @JsonDeserialize(using = LocalDateDeserializer.class)
        @JsonSerialize(using = LocalDateSerializer.class)
        private LocalDate maturityDate;
        @JsonFormat(pattern = "yyyyMMdd")
        @JsonDeserialize(using = LocalDateDeserializer.class)
        @JsonSerialize(using = LocalDateSerializer.class)
        private LocalDate entryDate;
    }
    

    In case you have POJO with multiple LocalDate fields it's better to configure mapper instead of POJO. It can be as simple as https://stackoverflow.com/a/35062824/1282532 if you are using ISO-8601 values ("2019-01-31")

    In case you need to handle custom format the code will be like this:

    ObjectMapper mapper = new ObjectMapper();
    JavaTimeModule javaTimeModule = new JavaTimeModule();
    javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyyMMdd")));
    javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyyMMdd")));
    mapper.registerModule(javaTimeModule);
    

    The logic is written just once, it can be reused for multiple POJO

提交回复
热议问题