【问题标题】:Deserialize object from string从字符串反序列化对象
【发布时间】: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 中对我有用。

【问题讨论】:

    标签: kotlin jackson


    【解决方案1】:

    好的,看了一些关于JsonCreator注解的文档,原来它一定是这样的:

    class Ref @JsonCreator(mode = JsonCreator.Mode.DELEGATING) constructor(@JsonValue val name: String)
    

    JsonCreator.Mode.DELEGATING 让它像我想要的那样工作。

    UPD:甚至可以缩短它 - 自定义杰克逊注释。

    @Retention(AnnotationRetention.RUNTIME)
    @Target(AnnotationTarget.CONSTRUCTOR)
    @JacksonAnnotationsInside
    @JsonCreator(mode = JsonCreator.Mode.DELEGATING)
    annotation class JsonDelegating
    

    及用法:

    class Ref @JsonDelegating constructor(@JsonValue val name: String)
    

    【讨论】:

      【解决方案2】:

      只需将属性上的 @JsonValue 注释定位到它的 getter 方法,就可以避免完全注释数据类的构造函数,如下所示:

      class Ref(@get:JsonValue val name: String)
      

      值得注意的是@field:JsonValue 在这种情况下也工作。

      为什么您的原始代码和字段定位都无法按预期工作,我无法告诉您。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多