杰克逊的Json解析错误,在转换为java.time.LocalDateTime时发生InvalidDefinitionException

时间:2019-04-04 04:00:36

标签: java json jackson date-format

使用杰克逊库隐秘json字符串将Kotlin对象

错误

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.LocalDateTime` (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2019-01-14T18:50:31.856+09:00')
 at [Source: (String)"{"name": "Kolineer", "age": "26", "messages" : ["message a","message b"],"transacted_at":"2019-01-14T18:50:31.856+09:00"}"; line: 1, column: 90] (through reference chain: com.test.utils.Person["transacted_at"])

这是代码

data class Person(val name: String, val age: Int, val messages: List<String>,
                  @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
                  @JsonProperty("transacted_at")
                  val transactedAt: LocalDateTime )

fun main(args: Array<String>) {

    val json = """{"name": "Kolineer", "age": "26", "messages" : ["message a","message b"],"transacted_at":"2019-01-14T18:50:31.856+09:00"}"""
    val mapper = jacksonObjectMapper()
    mapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS, false);
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    var person: Person = mapper.readValue<Person>(json)
    println(person)
}

1 个答案:

答案 0 :(得分:0)

要序列化/反序列化Java 8日期/时间类,您需要使用此jackson模块。

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-jsr310</artifactId>
  <version>2.8.8</version>
</dependency>

要手动将该模块注册到ObjectMapper,

ObjectMapper mapper = new ObjectMapper();
mapper.findAndRegisterModules();

注意::尚不了解kotlin语法,请将上述Java代码转换为kotlin。