简体   繁体   中英

Spring RequestBody cannot parse datetime timezone correctly

I have a simple rest service to store time range, however, Spring cannot parse datetime format with timezone correctly.

the Entity is

@Data
@Entity
public class TimeRange {
@Setter(AccessLevel.NONE)
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(nullable = true)
private LocalDateTime startTime;

@Column(nullable = true)
private LocalDateTime endTime;
}

The controller is:

@PostMapping(path = "/time", consumes = "application/json", produces = "application/json")
public Boolean setTime(@RequestBody TimeRange timeRange) {
    timeRangeRepository.save(timeRange);
    return true;
}

and the actuall request is

url = f'http://localhost/api/time'
data = {
  "startTime": "2019-12-03T19:58:29.047820+08:00",
  "endTime": "2019-12-04T19:58:29.047820+08:00"}
resp = requests.post(url, json=data, timeout=10)
pprint(resp.json())

spring reported an error said:

 esolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: 
Cannot deserialize value of type `java.time.LocalDateTime` from String "2019-12- 

03T19:58:29.047820+08:00": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2019-12-03T19:58:29.047820+08:00' could not be parsed, unparsed text found at index 26; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type java.time.LocalDateTime from String "2019-12-03T19:58:29.047820+08:00": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2019-12- 03T19:58:29.047820+08:00' could not be parsed, unparsed text found at index 26 at

You have a date with offset, if all your date comes in the same format you can create a custom deserializer like this

public class CustomLocalDateTimeDeserializer extends StdDeserializer<LocalDateTime> {
   private static final long serialVersionUID = 1L;

    public CustomLocalDateTimeDeserializer () {
        this(null);
    }

    protected CustomLocalDateTimeDeserializer (Class<?> vc) {
        super(vc);
    }

    @Override
    public LocalDateTime deserialize(JsonParser arg0, DeserializationContext arg1)
        throws IOException, JsonProcessingException {
        return LocalDateTime.parse(arg0.getValueAsString(), DateTimeFormatter.ISO_OFFSET_DATE_TIME);
    }

}

and the annotate your fields with @JsonDeserialize

@JsonDeserialize(using = CustomLocalDateTimeDeserializer.class)
private LocalDateTime startTime;

@JsonDeserialize(using = CustomLocalDateTimeDeserializer.class)
private LocalDateTime endTime;

And if you want to serialize your dates with the same format, you have to create a custom serializer

使用以下内容注释您的 LocalDateTime 字段:

@JsonSerialize(using = LocalDateTimeSerializer.class)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM