简体   繁体   中英

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 . 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.

As I'm using Kotlin I would love the non java Annotated way to to it.

With the ObjectMapper that you're going to use to do the deserialization, first register a custom deserializer for the Specific class. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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