【问题标题】:Error "is not a JSONObject"错误“不是 JSONObject”
【发布时间】:2014-05-25 13:28:01
【问题描述】:

我有 JSON 字符串:

{ "products" : [ { "created_at" : "2014-04-09 23:10:15",
        "name" : "tessss",
        "pid" : "1",
        "price" : "10.00",
        "updated_at" : "0000-00-00 00:00:00"
      },
      { "created_at" : "2014-04-10 21:14:51",
        "name" : "avgs",
        "pid" : "2",
        "price" : "20.00",
        "updated_at" : "0000-00-00 00:00:00"
      }
    ],
  "success" : 1
}

我的代码是(行是 JSON 字符串):

JSONObject nodeRoot  = new JSONObject(line); 

// Creating a sub-JSONObject from another JSONObject
JSONObject nodeStats = nodeRoot.getJSONObject("products");

// Getting the value of a attribute in a JSONObject
String sSDR = nodeStats.getString("name");
System.out.println(sSDR);

当我运行时出现错误JSONObject["products"] is not a JSONObject.

【问题讨论】:

  • products 是一个数组而不是对象,请先阅读一些关于 json 的教程

标签: android mysql sql json


【解决方案1】:

{ 代表 JSONObject,[ 代表 JSONArray

在您的 json 产品中代表 JSONArray 而不是 Object

这样做来获取名称字符串。

JSONObject nodeRoot  = new JSONObject(line); 
JSONArray nodeStats = nodeRoot.getJSONArray("products");
for(int i=0; i < nodeStats.length();i++){
String sSDR = nodeStats.getJSONObject(i).getString("name");
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    • 2018-06-05
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多