简体   繁体   English

如何在Jackson中编写自定义属性反序列化器

[英]How to write custom property deserializers in jackson

I have a lot of different classes that have a property that needs custom deserialization. 我有很多不同的类,它们的属性需要自定义反序列化。

Example: 例:

data class Specific(val a: String, val b: String) // <-- Needs special deserialization
data class Foo(val value: String, val sp: Specific)
data class Bar(val something: Int, val sp: Specific)

I have tried creating a custom deserializer using the StdDeserializer . 我尝试使用StdDeserializer创建自定义解串器。 And this only works if I write the deserializer for the actual class ( Foo and Bar ), but I only want to write one for the Specific type. 而且这仅在我为实际的类( FooBar )编写反序列化器时才有效,但是我只想为Specific类型编写一个。

As I'm using Kotlin I would love the non java Annotated way to to it. 当我使用Kotlin时,我会喜欢使用非Java注释的方式。

With the ObjectMapper that you're going to use to do the deserialization, first register a custom deserializer for the Specific class. 使用要用于反序列化的ObjectMapper ,首先为Specific类注册一个自定义反序列化器。 It will then use that when deserializing instances of this class, regardless of whether you're deserializing them directly, or as a property of some other object being deserialized. 然后,在反序列化此类的实例时,无论您是直接对其进行反序列化,还是作为其他要反序列化的对象的属性,都将使用该方法。

For example you could do something like this: 例如,您可以执行以下操作:

class SpecificDeserializer() : StdDeserializer<Specific>(Specific::class.java) {
    override fun deserialize(p: JsonParser, ctxt: DeserializationContext): Specific {
        // Deserialize
    }
}

val mapper = jacksonObjectMapper()
mapper.registerModule(SimpleModule().also {
    it.addDeserializer(Specific::class.java, SpecificDeserializer())
})

val foo = mapper.readValue<Foo>(...

This is explained here . 在这里解释。 Note that for serialization the same approach can be taken. 注意,对于序列化,可以采用相同的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM