Akshay Patel
Akshay Patel

Reputation: 23

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"
        }
      ]
    }
  ]
}

Upvotes: 1

Views: 2738

Answers (2)

anehme
anehme

Reputation: 566

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();
        }

Upvotes: 2

Greg Moens
Greg Moens

Reputation: 1825

The Android SDK includes the org.json lib. You can use the JSONObject class.

String jsonString = /* obtain some JSON however you need to*/;
JSONObject root = new JSONObject(jsonString);
JSONObject sub1 = root.getJSONObject("sub1");

I omitted exception handling, but this is the basic idea.

Upvotes: 2

Related Questions