问题
I use Java 11 and want to serialize/deserialize LocalDate/LocalDateTime as String. Okay. I added dependency:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson.version}</version>
</dependency>
and module:
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper()
.registerModule(new JavaTimeModule())
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
}
When I send date to my app, it deserializes correctly:
{"profileId":12608,"birthDate":"2008-03-20","relativeType":"SON","cohabitants":true}
When I using objectMapper as bean, directly, it serializes correctly too:
{"code":"SUCCESS","id":868,"profileId":12608,"birthDate":"2008-03-20","relativeType":"SON","cohabitants":true}
But when it serializes with controller, it serializes as array:
{"code":"SUCCESS","id":868,"profileId":12608,"birthDate":[2008,3,20],"relativeType":"SON","cohabitants":true}
Problem is to deserialize date in body on controller. Controller is:
@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;
}
Please, advice me, what's problem and how to fix it.
回答1:
Add the @JsonFormat annotation to your birthDate field , or rather any date field and your ObjectMapper (Spring Boot or not) should respect the formatting, as long as you have the additional js310 dependency on your classpath.
@JsonFormat(pattern="yyyy-MM-dd")
private LocalDate birthDate;
来源:https://stackoverflow.com/questions/60925899/localdate-serialization-date-as-array