Java 8 LocalDate Jackson format

前端 未结 14 1258
傲寒
傲寒 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条回答
  •  我在风中等你
    2020-11-22 13:48

    Since LocalDateSerializer turns it into "[year,month,day]" (a json array) rather than "year-month-day" (a json string) by default, and since I don't want to require any special ObjectMapper setup (you can make LocalDateSerializer generate strings if you disable SerializationFeature.WRITE_DATES_AS_TIMESTAMPS but that requires additional setup to your ObjectMapper), I use the following:

    imports:

    import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
    import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
    

    code:

    // generates "yyyy-MM-dd" output
    @JsonSerialize(using = ToStringSerializer.class)
    // handles "yyyy-MM-dd" input just fine (note: "yyyy-M-d" format will not work)
    @JsonDeserialize(using = LocalDateDeserializer.class)
    private LocalDate localDate;
    

    And now I can just use new ObjectMapper() to read and write my objects without any special setup.

提交回复
热议问题