我有票类:
data class Ticket(
var contact_email : String? = null,
var date_opened : LocalDateTime? = null
)
但我在从字符串读取时出错:
我尝试添加注释但没有成功:
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([email protected], date_opened=2017-11-13T06:40)")
}
val inputJsonString = """{
"contact_email": "[email protected]",
"date_opened": "2017-11-13T06:40:00Z"
}""".trimIndent()
}
关于Kotlin 数据类和 LocalDateTime,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50627956/