在Android中获取嵌套的JSON对象和多个JSON对象的嵌套JSON数组中的字符串。

5

我需要将包含在复杂Json中的所有单个参数作为字符串访问。

例如:String people=...; String idPeople=...; 等等。

我尝试使用JSONTokeners,因为我尝试搜索类似的问题,并且对于简单的json,我没有问题,但我不知道如何正确获取这个参数:

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

请注意:数组 "people" 中对象的数量不一定为 2,可能包含 4 个或更多个人对象。

2个回答

21

我没有尝试过。 但我猜它可能会起作用。

    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");
        ...
    }

2
如果我们称您所发布的JSON为“myJsonString”,
JSonObject obj = new JSonObject(myJsonString);
JSonObject result = obj.getJSONObject("result");
JSonArray people = result.getJSONArray("people");
int numOfPeople = result.getInt("nPeople");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接