0

I want to recursively create a JSON tree from multiple strings. A string might like this:

.this.is:0.a.test 

The character string is interpreted as follows:

  • . is an object
  • : is an array
  • :0. is the first object in the array

The corresponding JSON looks like this

{
   "this":{
      "is":[
         {
            "a":{
               "test":"testvalue"
            }
         }
      ]
   }
}

My code looks like this:

public static JsonNode recursiveLimb(ArrayList<String> limb, Map<String, String> mappingBodyMap, BidiMap<String, String> bidiMap, JsonNode currentTree, String path) {

        if (!limb.isEmpty() && limb.get(0).equals(".")) {
            //object node

            String firstElem = limb.remove(0);
            String secondElem = limb.remove(0);
            //call recursion to build rest of tree
            JsonNode resultJN = recursiveLimb(limb, mappingBodyMap, bidiMap, currentTree, path + firstElem + secondElem);

            return mapper.createObjectNode().set(secondElem, resultJN);

        } else if (!limb.isEmpty() && limb.get(0).equals(":")) {
            //array node

            String firstElem = limb.remove(0);
            String secondElem = limb.remove(0);
            //call recursion to build rest of tree
            JsonNode resultJN = recursiveLimb(limb, mappingBodyMap, bidiMap, currentTree, path + firstElem + secondElem);

            return mapper.createArrayNode().add(resultJN);

        } else {
            //value node 

            String value = bidiMap.getKey(path);
            return new TextNode(mappingBodyMap.get(value));
        }
    }

This code returns all individual links of the tree. The problem is, I'm having a hard time putting them together. Hopefully someone can help me. Does someone have an idea what I can do?

1 Answer 1

1

I think instead of using this it would be easier to create a string and convert it to JSON at the end. Example: .life.is:0.so.good -> We start reading from the end;

  1. We find . we create so:{good=goodValue}
  2. We find :0. is:[{so:{good=goodValue}}]
  3. We find . life:{is:[{so:{good=goodValue}}]}
  4. We find the last . we added {life:{is:[{so:{good=goodValue}}]}}

I believe your solution is good, I just wanted to simplify the problem so it is still up to you.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes sounds good but how do you merge multiple of these jsons in the end?
GSON-JsonParser would be a good idea. Here is the link for examples, tutorials.jenkov.com/java-json/gson-jsonparser.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.