This may be helpful while searching keys present in nested objects and nested arrays. And this is a generic solution to all cases.
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MyClass
{
public static Object finalresult = null;
public static void main(String args[]) throws JSONException
{
System.out.println(myfunction(myjsonstring,key));
}
public static Object myfunction(JSONObject x,String y) throws JSONException
{
JSONArray keys = x.names();
for(int i=0;i<keys.length();i++)
{
if(finalresult!=null)
{
return finalresult; //To kill the recursion
}
String current_key = keys.get(i).toString();
if(current_key.equals(y))
{
finalresult=x.get(current_key);
return finalresult;
}
if(x.get(current_key).getClass().getName().equals("org.json.JSONObject"))
{
myfunction((JSONObject) x.get(current_key),y);
}
else if(x.get(current_key).getClass().getName().equals("org.json.JSONArray"))
{
for(int j=0;j<((JSONArray) x.get(current_key)).length();j++)
{
if(((JSONArray) x.get(current_key)).get(j).getClass().getName().equals("org.json.JSONObject"))
{
myfunction((JSONObject)((JSONArray) x.get(current_key)).get(j),y);
}
}
}
}
return null;
}
}
Possibilities:
Logic :