Java 8 LocalDate Jackson format

前端 未结 14 1051
傲寒
傲寒 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:44

    If your request contains an object like this:

    {
        "year": 1900,
        "month": 1,
        "day": 20
    }
    

    Then you can use:

    data class DateObject(
        val day: Int,
        val month: Int,
        val year: Int
    )
    class LocalDateConverter : StdConverter() {
        override fun convert(value: DateObject): LocalDate {
            return value.run { LocalDate.of(year, month, day) }
        }
    }
    

    Above the field:

    @JsonDeserialize(converter = LocalDateConverter::class)
    val dateOfBirth: LocalDate
    

    The code is in Kotlin but this would work for Java too of course.

提交回复
热议问题