How to find parent Json node while parsing a JSON

14,935

Solution 1

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.

Solution 2

Got it!

@Override
public void serialize(ObjectId value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
    JsonStreamContext parent = jgen.getOutputContext().getParent();
    // Win!
}
Share:
14,935
Optional
Author by

Optional

SOreadytohelp I am a java guy. Tag me in the comment of your question, if your question has remained unanswered (in category java, xml, jaxb ) over a long period of time (and if you are still looking for an answer). I may or may not have solution, but I will definitely try to find one. I am also learning javascript, in between, and trying to keep pace with the ecosystem.

Updated on June 07, 2022

Comments

  • Optional
    Optional almost 2 years

    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..

  • Addo Solutions
    Addo Solutions about 9 years
    That is not true, I am looking at the debugger output, and when serializing, JsonGenerator jgen has _writeContext which contains _parent and links all the way up the tree. It just looks like it is private :(
  • StaxMan
    StaxMan about 9 years
    No, it is absolutely true. You are talking about JsonGenerator which is not a tree, but streaming generator object. It has context (similar to JsonParser). But the question was about JSON Trees (JsonNode) which do NOT have such linkage. Original problem may well be solved by using streaming API.