【发布时间】:2021-07-04 17:19:11
【问题描述】:
我正在尝试从字符串反序列化对象,但出现“没有字符串参数构造函数/工厂方法从字符串值反序列化('test')”异常。
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
class KotlinJacksonTest : FunSpec({
val mapper = jacksonObjectMapper()
test("deserialize as string") {
class Ref @JsonCreator constructor(@JsonValue val name: String)
class Root(val ref: Ref)
val root = mapper.readValue<Root>(""" { "ref": "test"} """)
root.ref.name shouldBe "test"
}
})
我需要的是让杰克逊序列化我的对象,就好像它是一个字符串一样。 但它不断失败并出现以下错误:
Cannot construct instance of `KotlinJacksonTest$1$1$Ref` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('test')
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `KotlinJacksonTest$1$1$Ref` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('test')
at [Source: (String)" { "ref": "test"} "; line: 1, column: 11] (through reference chain: KotlinJacksonTest$1$1$Root["ref"])
我做错了什么?我清楚地记得当我需要做同样的事情但使用地图而不是字符串时,这在 java 中对我有用。
【问题讨论】: