Jackson+Kotlin模块:恩怨/模棱两可的属性名称定义(隐含名称'isFoo')

fslejnso  于 2022-11-08  发布在  Kotlin
关注(0)|答案(1)|浏览(140)

当与KotlinModule一起使用时,在Jackson中遇到了一个奇怪的行为。试图用isXxx-布尔和xxx-非布尔属性反序列化一个JSON对象。有什么解决方案可以处理这个问题吗?

data class FooObject(
        @JsonProperty("isFoo")
        val isFoo: Boolean,
        @JsonProperty("foo")
        val foo: String,
    )

    @Test
    fun `deserialization should work` (){
        val serialized = """
            {
              "isFoo": true,
              "foo": "bar"
            }
        """.trimIndent()

        val objectMapper: ObjectMapper = Jackson2ObjectMapperBuilder()
            .modules(KotlinModule())
            .build()

        val deserialized = objectMapper.readValue(serialized, FooObject::class.java)

        assertNotNull(deserialized)
    }

throws

结果

java.lang.IllegalStateException: Conflicting/ambiguous property name definitions (implicit name 'isFoo'): found multiple explicit names: [isFoo, foo], but also implicit accessor: [method org.dnltsk.Test$FooObject#getFoo()][visible=true,ignore=false,explicitName=false], [method org.dnltsk.Test$FooObject#isFoo()][visible=true,ignore=false,explicitName=false]

通过删除@JsonProperty-注解,异常变为

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Duplicate creator property "isFoo" (index 0 vs 1) for type `org.dnltsk.Test$FooObject` 
 at [Source: (String)"{
  "isFoo": true,
  "foo": "bar"
}"; line: 1, column: 1]
sczxawaw

sczxawaw1#

将以下注解添加到数据类的顶部:

@JsonAutoDetect(
    getterVisibility = JsonAutoDetect.Visibility.NONE,
    isGetterVisibility = JsonAutoDetect.Visibility.NONE,
)

相关问题