【问题标题】:Get String from json with nested json object and nested json arrays with multiple json object, in Android在Android中从带有嵌套json对象的json和带有多个json对象的嵌套json数组中获取字符串
【发布时间】:2012-03-20 13:12:40
【问题描述】:

我需要以字符串的形式访问复杂 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 个或更多人对象

【问题讨论】:

    标签: android json


    【解决方案1】:

    我没试过。 但我想它可能会起作用。

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

    【讨论】:

    • 这让我发疯了。我在objective-c之后涉足Android开发,但无法弄清楚。谢谢!
    • 在这个答案中有更多问题的答案。谢谢
    【解决方案2】:

    如果我们调用你发布的 json myJsonString,

    JSonObject obj = new JSonObject(myJsonString);
    JSonObject result = obj.getJSONObject("result");
    JSonArray people = result.getJSONArray("people");
    int numOfPeople = result.getInt("nPeople");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-15
      • 2019-08-11
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 2021-08-17
      • 2020-05-10
      • 1970-01-01
      相关资源
      最近更新 更多