-
-
Save virtualsafety/c6c5ec082bfca2de8f0166ce73105ae3 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 = ObjectMapperSingleTon.INSTANCE.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 ObjectMapperSingleTon.INSTANCE.convertValue(this, T::class.java) | |
} | |
object ObjectMapperSingleTon { | |
val INSTANCE : ObjectMapper = ObjectMapper().apply {this.registerModule(KotlinModule())} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment