错误"不是JSONObject"

时间:2014-04-11 11:49:20

标签: android mysql sql json

我有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.

1 个答案:

答案 0 :(得分:5)

{表示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");
 }