Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use dot navigation in Jackson JsonNode

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?

like image 511
Luís Soares Avatar asked Oct 15 '22 04:10

Luís Soares


People also ask

How do you read a JsonNode?

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.

What is the difference between ObjectNode and JsonNode?

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.

How do I modify JsonNode?

The JsonNode class is immutable. That means we cannot modify it.


1 Answers

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");
like image 168
Deadpool Avatar answered Nov 01 '22 15:11

Deadpool