【问题标题】:items of type org.json.JSONArray cannot be converted to JSONObjectorg.json.JSONArray 类型的项目无法转换为 JSONObject
【发布时间】:2019-12-29 00:33:21
【问题描述】:

我遇到了一个问题。当我尝试接收该值时,我收到items of type org.json.JSONArray cannot be converted to JSONObject 的错误。我该如何解决这个问题?

JSONObject jsonObject = new JSONObject(response);
JSONObject snippet = jsonObject.getJSONObject("items");
String t = snippet.getString("rating");

【问题讨论】:

  • 错误信息试图告诉你一些事情......
  • 考虑改用 Gson。

标签: java android json youtube-api


【解决方案1】:

只需从 getJSONObject 更改为 items 属性的 getJSONArray。

JSONArray snippet = jsonObject.getJSONArray("items");

【讨论】:

    【解决方案2】:

    [..] 表示它应该是一个 JSONArray,{..} 表示它应该是一个 JSONObject。

    这样做:

    JSONArray snippet = jsonObject.getJSONArray("items");
    

    具有包含在 [] 中的值的 JSON 表示数组,这是大多数编程语言中的常见做法,{} 表示纯 JSON 实体。 因此,

    当语法为 {} 时,这是 JSONObject

    当语法为 [] 时,这是 JSONArray

    【讨论】:

    • 我们应该在给出解决方案的同时解释。不错。
    • 感谢您的提醒,已添加。
    • 太棒了,继续做同样的贡献。
    【解决方案3】:

    JSONArrayJSONObjects 的数组。您的 items json 节点是一个数组,而不是一个对象。替换

    JSONObject snippet = jsonObject.getJSONObject("items");
    

    JSONArray snippet = jsonObject.getJSONArray("items");
    

    然后从你的 sn-p 数组中你可以得到你需要的 item 对象

    JSONObject item = snippet.getJSONObject(0);
    

    从那里开始

    String t = item.getString("rating");
    

    【讨论】:

    • jsonarray 给了我 int 。但在屏幕截图中它只说评级。
    • JSONArray 有 n 个 JSON 对象节点,在您的情况下为 1(索引为 0)。此 JSONObject 有一个评级键。
    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 2013-12-13
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 2018-05-12
    相关资源
    最近更新 更多