Last active
October 17, 2021 08:59
-
-
Save remen/ad239a5b599fc03d371770c1abf7bfa3 to your computer and use it in GitHub Desktop.
Fun with kotlin and jackson
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
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
Cool :)