Вяч*_*шов 12 java spring objectmapper
我使用 Java 11 并希望将 LocalDate/LocalDateTime 序列化/反序列化为字符串。好的。我添加了依赖:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson.version}</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
和模块:
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper()
.registerModule(new JavaTimeModule())
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
}
Run Code Online (Sandbox Code Playgroud)
当我将日期发送到我的应用程序时,它会正确反序列化:
{"profileId":12608,"birthDate":"2008-03-20","relativeType":"SON","cohabitants":true}
Run Code Online (Sandbox Code Playgroud)
当我直接使用 objectMapper 作为 bean 时,它也可以正确序列化:
{"code":"SUCCESS","id":868,"profileId":12608,"birthDate":"2008-03-20","relativeType":"SON","cohabitants":true}
Run Code Online (Sandbox Code Playgroud)
但是当它与控制器序列化时,它序列化为数组:
{"code":"SUCCESS","id":868,"profileId":12608,"birthDate":[2008,3,20],"relativeType":"SON","cohabitants":true}
Run Code Online (Sandbox Code Playgroud)
问题是在控制器上反序列化正文中的日期。控制器是:
@PostMapping
public Relative create(@Validated(Validation.Create.class) @RequestBody Relative relative) {
return service.create(relative);
}
Run Code Online (Sandbox Code Playgroud)
相对类:
@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;
}
Run Code Online (Sandbox Code Playgroud)
请给我建议,有什么问题以及如何解决它。
mar*_*rco 22
将@JsonFormat 注释添加到您的birthDate字段,或者更确切地说,任何日期字段,并且您的ObjectMapper(无论是否是Spring Boot)都应该遵守格式,只要您的类路径有额外的js310依赖项。
@JsonFormat(pattern="yyyy-MM-dd")
private LocalDate birthDate;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10561 次 |
| 最近记录: |