Mullinsangebn
Mullinsangebn

Reputation: 133

Android parsing json object inside array

I want parse details of "name" and "id" here is my json and android code

{
  "main": {
    "details": [
      {
        "name": "name1", 
        "id": "id1"
      }, 
      {
        "name": "name2", 
        "id": "id2"
      }
     ] 
   } 
 }

and my code is:

try {
    JSONObject jsono = new JSONObject(url);
    SONArray jarray = jsono.getJSONArray("main");

    for (int i = 0; i < jarray.length(); i++) {
    JSONObject object = jarray.getJSONObject(i);

        Actors actor = new Actors();
        actor.setLink(object.getString("name"));
        actor.setImage(object.getString("id"));
        actorsList.add(actor);
        }
    return true;
}

I want out put "id" and "name"

Upvotes: 0

Views: 1041

Answers (4)

Samuil Yanovski
Samuil Yanovski

Reputation: 2867

You have a JSONObject "main", containing a JSONOArray "details". This means you have to call getJSONObject("main").getJSONArray("details");

If you are going to such parsing multiple times, I'd recommend you to take a look at Gson - it is much easier with it. You have to set a SerializableName attribute to the link and image fields of the Actor class and Gson will take care to map them with the values from the json.

Upvotes: 0

Rathan Kumar
Rathan Kumar

Reputation: 2577

try Like this:

JSONObject totalObject = new JSONObject(result);
        JSONObject mainObject = totalObject.getJSONObject("main");
        JSONArray jsonArray = mainObject.getJSONArray("details");
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject object = (JSONObject) jsonArray.get(i);
              Actors actor = new Actors();
                actor.setLink(object.getString("name"));
                actor.setImage(object.getString("id"));
                actorsList.add(actor);
        }

Upvotes: 2

nikis
nikis

Reputation: 11244

main is JSONObject, details is JSONArray, so the correct code to declare jarray is the following:

JSONArray jarray = jsono.getJSONObject("main").getJSONArray("details");

Upvotes: 0

Avishek Das
Avishek Das

Reputation: 699

Follow by this way:

try {
JSONObject jsono = new JSONObject(url);
SONArray jarray = jsono.getJSONArray("main");

for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);

    String name = object.getString("name");
    String id = object.getString("id");
    }
return true;
}

Upvotes: 0

Related Questions