Search code examples
javajsonspringdatetimelocaldate

Formatting JSON data with "ObjectMapper"


I have a field:

@NotNull
    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
    private LocalDate date;

But when I get data with JSON format - it is another:

"date":{"year":2020,"month":"JANUARY","monthValue":1,"dayOfMonth":6,"dayOfWeek":"MONDAY","dayOfYear":6,"era":"CE","chronology":{"calendarType":"iso8601","id":"ISO"},"leapYear":true}

How to fix it?


Solution

  • You could write a custom serializer/deserializer for it.

    @JsonDeserialize(using = LocalDateDeserializer.class)
    @JsonSerialize(using = LocalDateSerializer.class)
    private LocalDate date;
    

    This article goes into more detail on how you can create these classes - https://kodejava.org/how-to-format-localdate-object-using-jackson/