Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get String from json with nested json object and nested json arrays with multiple json object, in Android

Tags:

json

android

I need to access as String all the single parameters contained in a complex Json.

for example String people=...; String idPeople=...; etc.

I have tried to use the JSONTokeners, as I have tried to search for similar question, and for simple json I haven't problem but I don't know how to get the parameters correctly from this:

{"id":1,"error":null,"result":
  {"nPeople":2,
    "people":[
            {"namePeople":"Inca",
             "power":"1235",
             "location":"asdfghjja",
             "idPeople":189,
             "mainItems":"brownGem",
             "verified":false,
             "description":"Lorem impsum bla bla",
             "linkAvatar":"avatar_12.jpg",
             "longitude":16.2434263,
             "latitude":89.355118},

            {"namePeople":"Maya",
             "power":"1235",
             "location":"hcjkjhljhl",
             "idPeople":119,
             "mainItems":"greenstone",
             "verified":false,
             "description":"Lorem impsum bla bla",
             "linkAvatar":"avatar_6.jpg",
             "longitude":16.2434263,
             "latitude":89.3551185}]
    }
}

NB the numbers of object in the array people is not always 2... and may contains 4 or more people object

like image 894
AndreaF Avatar asked Mar 20 '12 13:03

AndreaF


2 Answers

I've not tried. But i guess it may work.

    JSONObject obj = new JSONObject(jsonString);
    String id = obj.getString("id");
    String error = obj.getString("error");
    JSONObject result = obj.getJSONObject("result");
    int nPeople = result.getInt("nPeople");
    JSONArray people = result.getJSONArray("people");
    for(int i = 0 ; i < people.length() ; i++){
        JSONObject p = (JSONObject)people.get(i);
        String namePeople = p.getString("namePeople");
        ...
    }
like image 116
Ethan Liou Avatar answered Sep 19 '22 22:09

Ethan Liou


if we call the json you post myJsonString,

JSonObject obj = new JSonObject(myJsonString);
JSonObject result = obj.getJSONObject("result");
JSonArray people = result.getJSONArray("people");
int numOfPeople = result.getInt("nPeople");
like image 28
Blackbelt Avatar answered Sep 23 '22 22:09

Blackbelt