Search code examples
androidandroid-studiokotlinjacksonjackson-databind

How to Deserialise the Jackson SNAKE CASE object mapper into CAMEL CASE data class model in Kotlin?


I have serialised the data class model "ProfileInfo" using

val jsonString = jacksonObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE).writeValueAsString(profileInfo)

but when I deserialise the jsonString into data class model using

val profileInfo: ProfileInfo = jacksonObjectMapper().readValue<ProfileInfo>(jsonString)

only the fields without underscores receiving the value. other fields with underscores assigned as null. Could anybody help me about how to deserialise using Jackson object mapper.


Solution

  • Each call to the jacksonObjectMapper() creates a new ObjectMapper, so either:

    • use the same object mapper for both, serialization and deserialization
    val mapper = jacksonObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
    val jsonString = mapper.writeValueAsString(profileInfo)
    ...
    val profileInfo: ProfileInfo = mapper.readValue(jsonString)
    
    • configure property naming strategy for deserialization the same way, you are doing it for serialization
    val profileInfo: ProfileInfo = jacksonObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE).readValue(jsonString)