SPRING MVC DateTimeFormat error

2019-08-27 04:23发布

问题:

Im trying to make a website using Spring + Angular JS and my current problem is i used POSTMAN to post a JSON statement as below:

{
    "id": 12345,
    "checkin" : "2017-03-01",
    "checkout" : "2017-03-05"
}

and then this error pops up: enter image description here

"Type definition error: [simple type, class java.time.LocalDate]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of java.time.LocalDate (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2017-03-01')"

Resource Code:

@RequestMapping(path = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
        consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<ReservationResponse> createReservation(
        @RequestBody
        ReservationRequest reservationRequest){
    return new ResponseEntity<>(new ReservationResponse(), HttpStatus.CREATED);
}

Model Code:

public class ReservationRequest {
    private Long id;
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
    private LocalDate checkin;
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
    private LocalDate checkout;}

APIConfig Code:

@Bean
@Primary
public ObjectMapper objectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModules(new JavaTimeModule());
    return new ObjectMapper();
}

Application Properties:

spring.jackson.serialization.write-dates-as-timestamps=false

Build Gradle:

compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310', version: '2.8.7'

回答1:

We also faced the same issue and after defining a converter it worked fine. You can add below code in the application and it should work fine. You can change the date format as per your need.

@Bean
    public MappingJackson2HttpMessageConverter customJackson2HttpMessageConverter() {
       MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
       ObjectMapper objectMapper = new ObjectMapper();
          objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
          objectMapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS, true);
          objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
          objectMapper.setDateFormat(new SimpleDateFormat("dd MMM yyyy hh:mm:ss a"));
      jsonConverter.setObjectMapper(objectMapper);

      return jsonConverter;
     }


回答2:

I was working through the same tutorial and encountered the same problem. What made my code work was to change the return value of the objectMapper() method in API Config Code from new ObjectMapper() to objectMapper.