Java 8 LocalDate Jackson format

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

    In configuration class define LocalDateSerializer and LocalDateDeserializer class and register them to ObjectMapper via JavaTimeModule like below:

    @Configuration
    public class AppConfig
    {
    @Bean
        public ObjectMapper objectMapper()
        {
            ObjectMapper mapper = new ObjectMapper();
            mapper.setSerializationInclusion(Include.NON_EMPTY);
            //other mapper configs
            // Customize de-serialization
    
    
            JavaTimeModule javaTimeModule = new JavaTimeModule();
            javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer());
            javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer());
            mapper.registerModule(javaTimeModule);
    
            return mapper;
        }
    
        public class LocalDateSerializer extends JsonSerializer<LocalDate> {
            @Override
            public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                gen.writeString(value.format(Constant.DATE_TIME_FORMATTER));
            }
        }
    
        public class LocalDateDeserializer extends JsonDeserializer<LocalDate> {
    
            @Override
            public LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
                return LocalDate.parse(p.getValueAsString(), Constant.DATE_TIME_FORMATTER);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 13:35

    @JsonSerialize and @JsonDeserialize worked fine for me. They eliminate the need to import the additional jsr310 module:

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

    Deserializer:

    public class LocalDateDeserializer extends StdDeserializer<LocalDate> {
    
        private static final long serialVersionUID = 1L;
    
        protected LocalDateDeserializer() {
            super(LocalDate.class);
        }
    
    
        @Override
        public LocalDate deserialize(JsonParser jp, DeserializationContext ctxt)
                throws IOException, JsonProcessingException {
            return LocalDate.parse(jp.readValueAs(String.class));
        }
    
    }
    

    Serializer:

    public class LocalDateSerializer extends StdSerializer<LocalDate> {
    
        private static final long serialVersionUID = 1L;
    
        public LocalDateSerializer(){
            super(LocalDate.class);
        }
    
        @Override
        public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider sp) throws IOException, JsonProcessingException {
            gen.writeString(value.format(DateTimeFormatter.ISO_LOCAL_DATE));
        }
    }
    
    0 讨论(0)
  • 2020-11-22 13:35

    The following annotation worked fine for me.

    No extra dependencies needed.

        @JsonProperty("created_at")
        @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
        @JsonDeserialize(using = LocalDateTimeDeserializer.class)
        @JsonSerialize(using = LocalDateTimeSerializer.class)
        private LocalDateTime createdAt;
    
    0 讨论(0)
  • 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<DateObject, LocalDate>() {
        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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 13:50
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    private LocalDateTime createdDate;
    
    0 讨论(0)
提交回复
热议问题