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?