Search code examples
javaandroidjsonandroid-studioandroid-json

How to fetch json inside json inside another json?


I am new to android and json. I want to implement some logic where i can get the data from sub1 from json inside json inside another json. Is there any way to get that data?

This is how my json file looks like.

{
  "Aeronautical": [],
  "Automobile": [],
  "Civil": [],
  "Computer": [
    {
      "sub1": [
        {
          "id": "1",
          "name": "name1",
          "year": "2019",
          "url": "some_url"
        },
        {
          "id": "2",
          "name": "Name 2",
          "year": "2018",
          "url": "some url"
        },
        {
          "id": "3",
          "name": "Name 4",
          "year": "2018",
          "url": "some url"
        }
      ]
    }
  ]
}

Solution

  • sub1 is inside another array , so first you should get data from computer array

       JSONObject obj = null;
            try {
                obj = new JSONObject(json);
    
            JSONArray arr = obj.getJSONArray("Computer");
    
            for (int i = 0; i < arr.length(); i++)
            {
                JSONObject obj_computers = arr.getJSONObject(i);
                JSONArray sub1 = obj_computers.getJSONArray("sub1");
    
                for (int j = 0; j < sub1 .length(); j++)
                {
                    JSONObject sub1_data = sub1.getJSONObject(j);
                    Log.i("test" ,sub1_data.toString());
                }
            }
            } catch (JSONException e) {
                e.printStackTrace();
            }