Unable to convert String to Date by requestBody in spring

前端 未结 2 1973
囚心锁ツ
囚心锁ツ 2020-12-17 22:18

I have the below Code :

DTO :

 Class MyDTO {
        import java.util.Date;
        private Date dateOfBirth;

        public Date g         


        
相关标签:
2条回答
  • 2020-12-17 22:41

    List itemCreate a class to extend JsonDeserializer

    public class CustomJsonDateDeserializer extends JsonDeserializer<Date> {
        @Override
        public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            String date = jsonParser.getText();
            try {
                return format.parse(date);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
    }
    

    Use @JsonDeserialize(using = CustomJsonDateDeserializer.class) annotation on setter methods.

    Thanks @Varun Achar answer, url

    0 讨论(0)
  • 2020-12-17 23:00

    @DateTimeFormat is for form backing (command) objects. Your JSON is processed (by default) by Jackson's ObjectMapper in Spring's MappingJackson2HttpMessageConverter (assuming the latest version of Jackson). This ObjectMapper has a number of default date formats it can handle. It seems yyyy-mm-dd is one of them, but dd-mm-yyyy is not.

    You'll need to register your own date format with a ObjectMapper and register that ObjectMapper with the MappingJackson2HttpMessageConverter. Here are various ways to do that :

    • Configuring ObjectMapper in Spring
    • Spring, Jackson and Customization (e.g. CustomDeserializer)

    Alternatively, you can use a JsonDeserializer on either your whole class or one of its fields (the date). Examples in the link below

    • Right way to write JSON deserializer in Spring or extend it
    • How to deserialize JS date using Jackson?
    0 讨论(0)
提交回复
热议问题