gpt4 book ai didi

Kotlin 数据类和 LocalDateTime

转载 作者:行者123 更新时间:2023-12-02 12:15:31 31 4
gpt4 key购买 nike

我有票类:

data class Ticket(
var contact_email : String? = null,
var date_opened : LocalDateTime? = null
)

但我在从字符串读取时出错:

Caused by: 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 ('2017-11-13T06:40:00Z') at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: rnd_classifier.model.Ticket["date_opened"])



我尝试添加注释但没有成功:
data class Ticket(
var contact_email : String? = null,

@JsonSerialize(using = ToStringSerializer::class)
@JsonDeserialize(using = LocalDateTimeDeserializer::class)
var date_opened : LocalDateTime? = null
)

如何修复它?

最佳答案

您的问题更多是关于 jackson 而不是 kotlin。
serialize/deserialize java 8 java.time with Jackson JSON mapper 中所述

你需要添加一个额外的gradle依赖来解决它

implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.5")

之后它应该工作
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import org.testng.annotations.Test
import java.time.LocalDateTime

class SoTest {

data class Ticket(
var contact_email: String? = null,
var date_opened: LocalDateTime? = null
)

@Test
fun checkSerialize() {
val mapper = ObjectMapper()
mapper.registerModule(JavaTimeModule())
val ticket = mapper.readValue(inputJsonString, Ticket::class.java)
assert ("$ticket"=="Ticket(contact_email=contact@ema.il, date_opened=2017-11-13T06:40)")
}

val inputJsonString = """{
"contact_email": "contact@ema.il",
"date_opened": "2017-11-13T06:40:00Z"
}""".trimIndent()

}

关于Kotlin 数据类和 LocalDateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50627956/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com