我使用Java 11,并希望将LocalDate / LocalDateTime序列化/反序列化为String。好的。我添加了依赖性:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson.version}</version>
</dependency>
和模块:
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper()
.registerModule(new JavaTimeModule())
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
}
当我向应用程序发送日期时,它会正确反序列化:
{"profileId":12608,"birthDate":"2008-03-20","relativeType":"SON","cohabitants":true}
当我直接将objectMapper用作bean时,它也正确地序列化了:
{"code":"SUCCESS","id":868,"profileId":12608,"birthDate":"2008-03-20","relativeType":"SON","cohabitants":true}
但是当它与控制器序列化时,它将序列化为数组:
{"code":"SUCCESS","id":868,"profileId":12608,"birthDate":[2008,3,20],"relativeType":"SON","cohabitants":true}
问题是在控制器上的正文中反序列化日期。控制器是:
@PostMapping
public Relative create(@Validated(Validation.Create.class) @RequestBody Relative relative) {
return service.create(relative);
}
Relative.class:
@Getter
@Setter
@ToString(callSuper = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Relative extends MortgageResponse {
@Null(groups = Validation.Create.class)
@NotNull(groups = Validation.Update.class)
private Long id;
@NotNull
private Long profileId;
private LocalDate birthDate;
private RelativeType relativeType;
private Boolean cohabitants;
}
请给我建议,有什么问题以及如何解决。
在您的birthDate或任何日期字段上添加@JsonFormat批注。