I have the following code:
private val parsed = ObjectMapper().readTree(vcap)
parsed.get("spaces")?.firstOrNull()?.get("block1")?.asText()
I'd like to use dot notation for navigating (for readibility reasons). Something like:
private val parsed = ObjectMapper().readTree(vcap)
parsed.get("spaces[0].block1")?.asText()
Is it possible?
A JsonNode is Jackson's tree model for JSON and it can read JSON into a JsonNode instance and write a JsonNode out to JSON. To read JSON into a JsonNode with Jackson by creating ObjectMapper instance and call the readValue() method. We can access a field, array or nested object using the get() method of JsonNode class.
JsonNode is a base class that ObjectNode and ArrayNode extend. JsonNode represents any valid Json structure whereas ObjectNode and ArrayNode are particular implementations for objects (aka maps) and arrays, respectively.
The JsonNode class is immutable. That means we cannot modify it.
If you are using jackson greater than 2.3
then you can simply use JsonPointer expression
parsed.at("/spaces/0/block1")?.asText()
Of if you wanna use dot navigation which is called json pathing you can use Jayway JsonPath
ReadContext ctx = JsonPath.parse(vcap);
ctx.read("$.spaces[0].block1");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With