Skip to content

Instantly share code, notes, and snippets.

@remen
Last active October 17, 2021 08:59
Show Gist options
  • Save remen/ad239a5b599fc03d371770c1abf7bfa3 to your computer and use it in GitHub Desktop.
Save remen/ad239a5b599fc03d371770c1abf7bfa3 to your computer and use it in GitHub Desktop.
Fun with kotlin and jackson
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
fun main(args: Array<String>) {
val jsonString : String = """
{
"authors" : [
{
"name" : "Kalle Jönsson",
"age" : 30
}
]
}
"""
val jsonNode = objectMapper.readTree(jsonString)
// Vanilla jackson
println(jsonNode["authors"][0]["name"].asText())
println(jsonNode["authors"][0]["age"].asInt())
// With our new "cast()" function where type is inferred from left hand side
val name : String = jsonNode["authors"][0]["name"].cast()
println(name)
// or explicitly as a type parameter to the cast functions
println(jsonNode["authors"][0]["age"].cast<Int>())
// But the really cool part is that you can cast to a domain object
// without having to have to map *everything*.
val author : Author = jsonNode["authors"][0].cast()
println(author.name)
println(author.age)
}
data class Author(val name : String, val age : Int)
inline fun <reified T : Any> JsonNode.cast() : T {
return objectMapper.convertValue(this, T::class.java)
}
val objectMapper = jacksonObjectMapper()
@MuyembeII
Copy link

Nice, about to try this, Anymore examples regarding this technique and derserialization

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment