【问题标题】:Json parsing problems in Android StudioAndroid Studio 中的 Json 解析问题
【发布时间】:2016-12-10 13:35:05
【问题描述】:

我在使用 Android Studio 中的 JSON API 时遇到了一些问题 我一直在观看和阅读很多示例,但仍然无法弄清楚如何提取我需要的数据...

几个小时后,我终于明白了我想提取的点:

JSONObject subObj = jsonObject.getJSONObject("response");

内容如下:

{
    "hereNow": {
    "count": 1,
    "items": [
      {
        "id": "xxxxxxxxxx",
        "createdAt": xxxxxxxxxx,
        "type": "checkin",
        "timeZoneOffset": 60,
        "user": {
          "id": "xxxxxxx",
          "firstName": "xxxxxxxx",
          "lastName": "xxxxxxxxxx",
          "gender": "male",
          "relationship": "friend",
          "photo": {
            "prefix": "xxxxxxxxx",
            "suffix": "xxxxxxxxxx"
          }
        },
        "likes": {
          "count": 0,
          "groups": [

      ]
    },
    "like": false
      }
    ]
  }
}

现在的问题是:如何提取用户对象?我一直在尝试很多事情

JSONObject

JSONArray

但我不断得到这个:

Attempt to invoke virtual method 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference

有人可以帮帮我吗? 请不要将我重定向到另一个主题,因为总的来说我理解 JSON,只是在这种特殊情况下不是......

提前致谢。

【问题讨论】:

  • 尝试示例并阅读explanation here,如果您在阅读后有疑问,请更新您的问题

标签: android arrays json api


【解决方案1】:

这应该适合你

    try{
        JSONArray array = subObj.getJSONObject("hereNow").getJSONArray("items");
        for(int index=0; index<array.length();index++){
            JSONObject itemsObj = array.getJSONObject(index);
            JSONObject userObj = itemsObj.getJSONObject("user");
            Log.d("Test", "Relationship "+userObj.get("relationship"));
        }   
    } catch (JSONException e) {
        e.printStackTrace();
    }

【讨论】:

  • 这行得通吗?如果是,请投票,以便其他有类似问题的人也知道。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-23
  • 2019-03-08
  • 1970-01-01
  • 2015-07-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多