1

我有一个简单的问题,自 2 天以来无法解决。作为 Android 的新手有时看起来很累人。但这里,

一个简单的 JSON 文件如下所示:

"results" : [
{
     "value1" : {
        "sub-value" : {
           "sub-sub-value1" : "This is one value",
           "sub-sub-value2" : "This is one more.."
        }
     },
     "value2" : "http://someURL.com",
     "value3" : "areferencejunkvalue",
  }
],
...<many such result sets>
 "status" : "status_value"
}

解析这个简单的 JSON 文件的代码如下。

try {
JSONArray results = json.getJSONArray("results");
JSONObject value1 = results.getJSONObject("value1");
JSONArray subvalue = locationGeom.getJSONArray("sub-value");

for (int i = 0; i < results.length(); i++) {
      // Gets data for value2,value3
      String value2 = results.getString("value2");
      String value3 = results.getString("value3");

      // Gets data from the sub-sub-value1
      String ssv1 = subvalue.getJSONObject(0).getString("sub-sub-value1").toString();
      // Gets data from the sub-sub-value2
      String ssv2 = subvalue.getJSONObject(0).getString("sub-sub-value2").toString();
    }
 } catch (JSONException e1) {
Log.e("E", "Issue is here..");
e1.printStackTrace();
}

现在的问题是:

05-06 23:39:07.846: W/System.err(378): org.json.JSONException: Value [JSONObject parsed] at results of type org.json.JSONArray cannot be converted to JSONObject

谁能告诉我这里哪里出错了?真诚感谢您的帮助。

4

1 回答 1

2

sub-value不是数组,而是对象,例如:

JSONArray results = json.getJSONArray("results");
JSONObject value1 = results.getJSONObject(0).getJSONObject("value1");
JSONObject subvalue = locationGeom.getJSONObject("sub-value");

基本的提取规则非常简单:

from \ get  |  JSONObject                     | JSONArray
------------+---------------------------------+--------------------------------
JSONObject  | jobj.getJSONObject(String key); | jobj.getJSONArray(String key);
JSONArray   | jobj.getJSONObject(int index);  | jobj.getJSONArray(int index);

另请参考:

于 2012-05-07T00:03:43.127 回答