【问题标题】:Unable to Parse JSONArray cannot be converted to JSONObject无法解析 JSONArray 无法转换为 JSONObject
【发布时间】:2021-07-25 19:05:58
【问题描述】:

这是我的 JSON(完整的 JSON 在这里:https://pastebin.com/kyPMWcTT):

 "replies": [
        [
           {
              "id": 2,
              "parent": 0,
              "author": 1,
              "author_name": "admin",
              "author_url": "http://localhost/wordpress",
              "date": "2021-05-02T08:38:00",
              "content": {
                 "rendered": "<p>Nice Blog, Awesome !</p>\n"
              },
              "link": "http://localhost/wordpress/2021/05/01/one-pot-thai-style-rice-noodles/#comment-2",
              "type": "comment",
             
              }
        ]

我正在尝试获取位于 content Object 内的 rendered 项目。 这是我尝试过的代码:

   JSONArray replyArray = embeddedObject.getJSONArray("replies");
                            for (int j = 0; j < replyArray.length(); j++) {
                                JSONObject contentObject = replyArray.getJSONObject(j);
                                JSONObject getContent = contentObject.getJSONObject("content");
                                String reply = getContent.getString("rendered");
                                Log.e("Reply is", reply);
                            }

但是,Logcat 的输出是:

Value at 0 of type org.json.JSONArray cannot be converted to JSONObject

如何解决这个问题?我究竟做错了什么 ?请指导

【问题讨论】:

  • 您的 JSON 出于某种原因有一个嵌套数组?如果您正确查看它,它将转到replies -&gt; array -&gt; array
  • @HenryTwist 那么,如何解析这个嵌套数组?它根本没有名字
  • 您可以使用JSONArray.getJSONArray 来获取您已经在代码中使用的数组中的项目。

标签: android json android-volley


【解决方案1】:

发生了什么?

我们试图在replies JSONArray 之后立即获取 JSONObject。但是,实际的content 位于以下层次结构中。

replies JSONObject -> JSONArray -> JSONArray -> ContentObject -> Content

解决方案

替换这个

JSONArray replyArray = embeddedObject.getJSONArray("replies");
for (int j = 0; j < replyArray.length(); j++) {
      JSONObject contentObject = replyArray.getJSONObject(j);
      JSONObject getContent = contentObject.getJSONObject("content");
      String reply = getContent.getString("rendered");
      Log.e("Reply is", reply);
}

有了这个

JSONArray replyArray = embeddedObject.getJSONArray("replies");
for (int j = 0; j < replyArray.length(); j++) {
      JSONArray replySubArray = replyArray.getJSONArray(j);
      for (int i = 0; i < replySubArray.length(); j++) {
            JSONObject contentObject = replySubArray.getJSONObject(i);
            JSONObject getContent = contentObject.getJSONObject("content");
            String reply = getContent.getString("rendered");
            Log.e("Reply is", reply);
      }
}

【讨论】:

  • 非常感谢好友!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多