默认情况下不支持Java8日期/时间类型`java.time.Instant`问题:
我很难理解 java.time.Instant 库。我不确定哪里没有实现 Instant 库的直接解决方案。我有一个 spring-boot 项目,我在 MongoDB 上创建了带有 CRUD 操作的 RESTful 服务。一切都很好,直到我在 DTO 中引入了 Instant updatedOn 和 Instant createdOn。
这是发生故障的 POST 响应的示例代码。
@Override
public ResponseEntity<ResponseDto> create(@RequestBody CLMDto CLMDto) {
CLMDto createdCLMDto =
CLMService.create(CLMDto);
return ResponseEntity.status(HttpStatus.CREATED)
.header(
RESPONSE_HEADER_LOCATION, CLM_URL + "/" + createdCLMDto.getId())
.body(ResponseDto.builder().value(createdCLMDto).build()); //--------------------->**Failing here**
}
我的回复 DTO 看起来像这样
@Data
@Builder
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
public class ResponseDto {
private Integer count;
private Object value;
private Object error;
private Object info;
}
和 CLMD
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AdminDataDto {
private Instant createdOn;
private Instant updatedOn;
@JsonProperty(value = "updatedByName", access = JsonProperty.Access.READ_ONLY)
private String updatedByName;
}
在调试器中,我注意到发生异常的地方变量 createdCLMDto 具有以下值
createdOn:Instant@193 "2021-03-27T11:53:24.774765300Z"
updatedByName:test
updatedOn:Instant@195 "2021-03-27T11:53:24.774765300Z"
因为我使用的是 Lombok 插件,所以我无法在内部调试并找到自动生成代码的根本原因。我不是在寻找解决方案,而是在寻找可能出现问题的建议。我的确切错误是
Type definition error: [simple type, class java.time.Instant]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
Java 8 date/time type `java.time.Instant` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable
handling (through reference chain:
com.abc.service.dto.ResponseDto["value"]->com.abc.dto.AdminDataDto["createdOn"])",
不用说,但我已经尝试了此处提供的解决方案来更新 Maven 库,但没有成功。我在这个库周围的 StackOverflow 上发现了很多问题,但没有人解释实现这个库的最简单方法。
我已经在 pom.xml 中遵循依赖项
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
我已经尝试过这里提供的解决方案
Java 8 date time types serialized as object with Spring Boot
回答
您的项目中是否有以下工件?
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
根据spring 源代码,如果类com.fasterxml.jackson.datatype.jsr310.JavaTimeModule存在于您的类路径中,JavaTimeModule则应注册
- You shouldn't create the object mapper by yourself, normally spring boot do it for you. Do you have `@SpringBootApplication` annotation in your code (this annotation declare `@EnableAutoConfiguration` which configure your application automatically depending on what you have in your classpath and properties)
THE END
二维码