Skip to content

Instantly share code, notes, and snippets.

@Jellymath
Created January 27, 2020 13:35
Show Gist options
  • Save Jellymath/74b97e32f9241bbef75134ad30e0c490 to your computer and use it in GitHub Desktop.
Save Jellymath/74b97e32f9241bbef75134ad30e0c490 to your computer and use it in GitHub Desktop.
Provide unsafe version of single function get
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
val defaultMapper = ObjectMapper()
val defaultMapperContext = MapperContext(defaultMapper)
class MapperContext(val mapper: ObjectMapper) {
inline operator fun <reified T> JsonNode.get(vararg params: Any): T {
var current = this
for (param in params) {
current = when (param) {
is Int -> current[param]
is String -> current[param]
else -> throw IllegalArgumentException("Only String or Int allowed")
}
}
return mapper.treeToValue(current, T::class.java)
}
inline operator fun <reified T> String.get(vararg params: Any): T {
return mapper.readTree(this).get(*params)
}
}
fun <T> ObjectMapper.use(action: MapperContext.() -> T): T = MapperContext(this).action()
inline operator fun <reified T> JsonNode.get(vararg params: Any): T = with(defaultMapperContext) { this@get.get(*params) }
inline operator fun <reified T> String.get(vararg params: Any): T = with(defaultMapperContext) { this@get.get(*params) }
fun main() {
val json = """
{
"somebody": {
"told": [
{
"me" :5
},
2,
"ping"
]
}
}
"""
val value: Int = json["somebody", "told", 0, "me"]
println(value)
val altValue: Int = defaultMapper.use { json["somebody", "told", 0, "me"] }
println(altValue)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment