0

I have an array which contains path values as shown below:

{"A/B1","A/B2","B2/C3","B2/C4"}

I want to create a json structure using this which should look like:

[
  {
    label : A,
    child : [
      {label : 'B1'},
      {label : 'B2',
       child : [
         {label : 'C3'},{label : 'C4'}
       ]
      }
    ]
  }
]

I want to do something like below:

package com.ds.test;

import java.util.Iterator;  
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Test {

    private static String pathArray[] = {"A/B1","A/B2","B2/C3","B2/C4"};
    private static JSONArray resultJson = null;

    private static void buildJson(String pathStr) throws JSONException{
        String elems[] = pathStr.split("/");
        String parent = "";
        for(int jj = 0; jj < elems.length; jj++){
            checkAndAdd(elems[jj],parent);
            parent = elems[jj];
        }

    }

    private static void checkAndAdd(String elem,String parent) throws JSONException{
        if(parent.isEmpty()){
            JSONObject obj = new JSONObject();
            obj.put("label",elem );
            resultJson.put(obj);
        }
        else{
            for(int jj = 0; jj < resultJson.length(); jj++){
                //to do;
                //if json element contains element with label = parent then add elem as child
                //to it.
            }
        }


    }

    public static void main(String[] args) throws Exception {

        resultJson = new JSONArray();

        for(int ii=0; ii < pathArray.length; ii++){
            buildJson(pathArray[ii]);
        }
    }

    }

But, I am not getting a way by which I can check if an element is already present so that I can add child array to it. I want to do it recursively, but not getting a way.

Can someone suggest me a way by which I can proceed? I am not asking for complete code help. I just need some logic to proceed? Can someone help me in this?

1 Answer 1

1

I would approach it as a graph problem or a tree problem. All you need to do is create a Graph or Tree with following vertices

A B2 B2 C3 C4.

Add correct edges to it. So now you have something like this

       A
     /   \
   B1     B2
  /    \  / \ 
 C1   C2  C3  C4

Now you just have to BFS or Level order traversal.

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

Comments

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.