Below is the json will be recieved from the partner application as input to perform operation at our end.
{"path":"/test1" ,"children":[{"path":"/test2"},{"path":"/test3","children":[{"path":"/test4","children":[{"path":"/test5"}]}]}]}
Value for children key is JsonArray. Children key might be nested n number of times as specified in json.
Below java class is used to parse mentioned json and as suggested in many forums that recursive program will consumes more time to execute. Please let me know better approach to parse this json.
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class TestJsonDynamic {
public static void parsejson(JSONArray json)
{
//System.out.println("Outer Array --- "+json);
for(int k=0;k<json.length();k++)
{
try {
JSONObject json2=(JSONObject)json.get(k);
if(json2.has("children"))
{
parsejson((JSONArray)json2.get("children"));
}
else
{
System.out.println("File Name "+json2.get("path"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
String str="{\"path\":\"/test1\" ,\"children\":[{\"path\":\"/test2\"},{\"path\":\"/test3\",\"children\":[{\"path\":\"/test4\",\"children\":[{\"path\":\"/test5\"}]}]}]}";
try {
System.out.println("Complete Json ---------> "+str);
JSONObject json=new JSONObject(str);
JSONArray jarr=(JSONArray)json.get("children");
System.out.println(jarr.length());
for(int i=0;i<jarr.length();i++)
{
JSONObject json1=(JSONObject)jarr.get(i);
System.out.println("Outer loop "+i);
if(json1.has("children"))
{
JSONArray jarr1=(JSONArray)json1.get("children");
for(int j=0;j<jarr1.length();j++)
{
JSONObject json2=(JSONObject)jarr1.get(j);
if(json2.has("children"))
{
parsejson((JSONArray)json2.get("children"));
}
else
{
System.out.println(json2.get("path"));
}
}
}
else
{
System.out.println(json1.get("path"));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}