Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find parent Json node while parsing a JSON

I am parsing a JSON Stream using Jackson.

API that I am using is ObjectMapper.readTree(..)

Consider following stream:

{
  "type": "array",
  "items": {
      "id": "http://example.com/item-schema",
      "type": "object",
      "additionalProperties": {"$ref": "#"}
  }
}

Now when I read additionalProperties, I figure out there is a "$ref" defined here. Now to resolve the reference, I need to go to its parent and figure out the id (to resolve the base schema).

I can't find any API to go to parent of JsonNode holding additionalProperties. Is there a way I can achieve this?

Info:

Why I need this is I need to find the base schema against which $ref has to be resolved. And to figure out base schema, I need to know the id of its parents..

like image 844
Optional Avatar asked Jan 02 '14 10:01

Optional


People also ask

How do I access JsonNode?

We can access a field, array or nested object using the get() method of JsonNode class. We can return a valid string representation using the asText() method and convert the value of the node to a Java int using the asInt() method of JsonNode class.

How do you traverse JsonNode?

Traverse JsonNode Graph You do so by iterating its nested fields (or nested elements in case of an array). Here is an example of traversing all nested fields of a JsonNode representing a JSON object or JSON array: public static void traverse(JsonNode root){ if(root. isObject()){ Iterator<String> fieldNames = root.

What is JsonNode Jackson?

JsonNode is one of the most used classes of Jackson. It is an immutable class; means we cannot actually build an object graph of JsonNode instances. Instead, we can create an object graph of the subclass of JsonNode, i.e., ObjectNode. com.fasterxml.jackson.databind.JsonNode.

What is the difference between a JSON object and a JSON node?

ObjectNode is a concrete implementation of JsonNode that maps a JSON object, and a JSON object is defined as following: An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace).


1 Answers

Jackson JSON Trees are singly-linked, there is no parent linkage. This has the benefit of reduced memory usage (since many leaf-level nodes can be shared) and slightly more efficient building, but downside of not being able to traverse up and down the hierarchy.

So you will need to keep track of that yourself, or use your own tree model.

like image 54
StaxMan Avatar answered Sep 21 '22 23:09

StaxMan