Jackson+Kotlin 组合报错Cannot construct instance of `java.time.LocalDateTime`

Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.cityos.entity.Licence` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (String)"{"id":1,"cd":"2019-09-09T09:25:27","v":"1.0"}"; line: 1, column: 2]
	at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67) ~[jackson-databind-2.9.9.jar:2.9.9]
	at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1452) ~[jackson-databind-2.9.9.jar:2.9.9]
	at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1028) ~[jackson-databind-2.9.9.jar:2.9.9]
	at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1297) ~[jackson-databind-2.9.9.jar:2.9.9]
	at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:326) ~[jackson-databind-2.9.9.jar:2.9.9]
	at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:159) ~[jackson-databind-2.9.9.jar:2.9.9]
	at com.fasterxml.jackson.databind.ObjectReader._bindAndClose(ObjectReader.java:1611) ~[jackson-databind-2.9.9.jar:2.9.9]
	at com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:1219) ~[jackson-databind-2.9.9.jar:2.9.9]
	at com.cityos.service.RuntimeService.scanLicence(RuntimeService.kt:63) ~[main/:na]
	at com.cityos.service.RuntimeService.run(RuntimeService.kt:33) ~[main/:na]
	at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:772) ~[spring-boot-2.1.8.RELEASE.jar:2.1.8.RELEASE]
	... 6 common frames omitted
data class Entity(
    val id:Int,
    val cd: LocalDateTime,
	val v: String
)

原因

Kotlin data class+Jackson存在一定兼容性问题

解决方案

# 增加两个模块 版本2.99请自行更改和Core版本一样
compile 'com.fasterxml.jackson.module:jackson-module-kotlin:2.9.9'
compile 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.9'
val bean = ObjectMapper().run {
                registerModules(JavaTimeModule(),KotlinModule())
                readerFor(Entity::class.java).readValue(your_json)
}

可能有用的文章

https://stackoverflow.com/questions/45863678/json-parse-error-can-not-construct-instance-of-java-time-localdate-no-string-a
https://www.baeldung.com/jackson-serialize-dates

你可能感兴趣的:(问题集)