Skip to content

Instantly share code, notes, and snippets.

@bastman
Created August 4, 2021 06:44
Show Gist options
  • Save bastman/9dc6ca449ebb7bc2373e541723c48ae6 to your computer and use it in GitHub Desktop.
Save bastman/9dc6ca449ebb7bc2373e541723c48ae6 to your computer and use it in GitHub Desktop.
jmespath extensions for jackson
fun ObjectMapper.convertValueAsJsonNode(value:Any?):JsonNode = convertValue(value, JsonNode::class.java)
inline fun <reified T> JsonNode.jq(
query: String,
noinline convert: (Any) -> T
): T {
val isNullable: Boolean = null is T
try {
val expression: Expression<JsonNode> = JmesPathJackson.compile(query)
val resultNode: JsonNode? = expression.search(this)
return when (resultNode) {
null -> null
else -> convert(resultNode)
} as T
} catch (all: Exception) {
val className:String = buildString {
append(T::class.qualifiedName)
if(isNullable) { append("?") }
}
error("Failed to jq JsonNode.$query as $className ! reason: ${all.message}")
}
}
object JmesPathJackson {
private val JACKSON_RUNTIME = JacksonRuntime()
private val runtime: JmesPath<JsonNode> = JACKSON_RUNTIME
fun compile(expression: String): Expression<JsonNode> = runtime.compile(expression)
fun search(input: JsonNode, expression: Expression<JsonNode>): JsonNode = expression.search(input)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment