问题描述
我正在使用 Spring Boot 2.4.5 并尝试使用 WebClient 请求另一个应用程序的 REST API。我知道另一个应用程序将请求的信息作为集合提供。
当我使用 Object[]
接收响应时:
Object[] ob = (Object[]) webClient
.get()
.uri(endpoint)
// .bodyValue(criteria)
.exchangetoMono(response -> {
if (response.statusCode()
.equals(HttpStatus.OK)) {
return response.bodyToMono(Object[].class);
} else if (response.statusCode()
.is4xxClientError()) {
return Mono.just("Error response");
} else {
return response.createException()
.flatMap(Mono::error);
}
}).block();
我可以看到我收到了一个包含所有值的 LinkedHashMap,包括一个字段:
date_of_declaration -> 2020-03-02T08:43:10
但是,如果可能的话,我想让 WebClient 立即将响应转换为指定的 DTO...
DeclarationDTO[] ob = (DeclarationDTO[]) webClient
.get()
.uri(endpoint)
// .bodyValue(criteria)
.exchangetoMono(response -> {
if (response.statusCode()
.equals(HttpStatus.OK)) {
return response.bodyToMono(DeclarationDTO[].class);
} else if (response.statusCode()
.is4xxClientError()) {
return Mono.just("Error response");
} else {
return response.createException()
.flatMap(Mono::error);
}
}).block();
...当 LocalDateTime 对象应该被反序列化时,我得到一个异常。
org.springframework.core.codec.DecodingException: JSON decoding error: Cannot deserialize value of type `java.time.LocalDateTime` from String "02-03-2020 01:20:00": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '02-03-2020 01:20:00' Could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {HourOfAmPm=1,NanoOfSecond=0,SecondOfMinute=0,MicroOfSecond=0,MinuteOfHour=20,MilliOfSecond=0},ISO resolved to 2020-03-02 of type java.time.format.Parsed; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDateTime` from String "02-03-2020 01:20:00": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '02-03-2020 01:20:00' Could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {HourOfAmPm=1,ISO resolved to 2020-03-02 of type java.time.format.Parsed
at [Source: (io.netty.buffer.ByteBufInputStream); line: 1,column: 1438] (through reference chain: java.lang.Object[][0]->de.xxx.myportal.api.infrastructure.dto.MyDTO["a_person"]->de.xxx.myportal.api.infrastructure.dto.APersonDTO["foobar"])
我认为 WebClient 有一个内部 ObjectMapper,所以也许可以在 WebClient 实例化期间修改这个 ObjectMapper? ...或者有没有更好的方法来告诉 Webclient 如何处理 LocalDateTime? ...也许是通过配置自定义的 WebClient 或...?
我无法解释,但在删除任何 JsonFormat 注释后,它开箱即用。 (奇怪!)
解决方法
这可能有助于https://www.baeldung.com/spring-boot-formatting-json-dates
在您的声明DTO中,您可以使用以下内容:
@JsonFormat(pattern="yyyy-MM-dd'T'HH:mm:ss")
@JsonProperty("date_of_declaration")
private LocalDateTime dateOfDeclaration;