Java 8 LocalDate Jackson format

前端 未结 14 1046
傲寒
傲寒 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 {
            @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 {
    
            @Override
            public LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
                return LocalDate.parse(p.getValueAsString(), Constant.DATE_TIME_FORMATTER);
            }
        }
    }
    

提交回复
热议问题