Created
August 4, 2021 06:44
-
-
Save bastman/9dc6ca449ebb7bc2373e541723c48ae6 to your computer and use it in GitHub Desktop.
jmespath extensions for jackson
This file contains 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
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