我在将JSON映射到具有localdateTime
的DTO时遇到了一个问题。
我跟踪了这个线程:JSON解析错误:无法构造java.time.LocalDate的实例:没有字符串参数构造函数/工厂方法来从字符串值反序列化
添加到build.gradle
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.11.0'
下面是DTO中的变量:
@Data
public class MyDto {
private Long teamId;
private Map<String, List<Long>> details;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime dateOccurred;
}
然后加了这个
public class MyApplication {
@Autowired
private ObjectMapper objectMapper;
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@PostConstruct
public void setUp() {
objectMapper.registerModule(new JavaTimeModule());
}
}
我错过什么了吗? 我得到了这个错误
org.springframework.messaging.converter.MessageConversionException: Could not read JSON: Cannot construct instance of `java.time.LocalDateTime` (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2020-06-16 11:12:46')
谢谢!
感谢@穆罕默德汗的引路人!
在这个答案中:spring boot的JSON Java 8 LocalDateTime格式
在spring引导中已经有一个设置,不需要@autowire
objectmapper
只需将其添加到application.properties
中即可
spring.jackson.serialization.write_dates_as_timestamps=false
并为Json反序列化器添加以下注释
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime dateOccurred;
谢谢!