Search code examples
jsonkotlinjacksondeserialization

Is there a way to deserialize Json into Kotlin data class and convert property types?


I have some json

{ 
    "name": "Foo",
    "age": 12,
    "id": "1234567890"
}

Currently, my data class I want to deserialize into looks like this

data class Example( val name: String, val age: Int, val id: String)

Is there a way to simply have the data class as

data class Example( val name: String, val age: Int, val id: Long)

Attention to the id type Long

I suppose this can be achieved through the use of an extension function that parses the data class into a separate data classes.

But I'd like to know if this is possible in any other way. I'm using Jackson for deserialization.


Solution

  • You don't have to do anything. Jackson automatically converts the String into a Long if it is possible:

    import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
    import com.fasterxml.jackson.module.kotlin.readValue
    
    data class C(
        val s: String,
        val n: Long
    )
    
    fun main() {
        val json = """{"s":"My string","n":"1234567890"}"""
    
        val mapper = jacksonObjectMapper()
        val c: C = mapper.readValue(json)
        println(c)  // prints "C(s=My string, n=1234567890)"
    }
    

    This automatic conversion is controlled by MapperFeature.ALLOW_COERCION_OF_SCALARS, which is enabled by default.