使用Java解码JSON对象数组

Jak*_*ake 3 java android json json-simple

我有如下JSON:

[{"0":"1","id":"1","1":"abc","name":"abc"},{"0":"2","id":"2","1":"xyz","name":"xyz"}]
Run Code Online (Sandbox Code Playgroud)

它是一个对象数组.

我需要使用Java解析它.我在以下网址使用该库:http: //code.google.com/p/json-simple/downloads/list

此链接的示例1近似于我的要求:http: //code.google.com/p/json-simple/wiki/DecodingExamples

我有以下代码:

/** Decode JSON */
// Assuming the JSON string is stored in jsonResult (String)

Object obj = JSONValue.parse(jsonResult);
JSONArray array = (JSONArray)obj;
JSONObject jsonObj = null;
for (int i=0;i<array.length();i++){
    try {
        jsonObj = (JSONObject) array.get(i);
    } catch (JSONException e) {
        e.printStackTrace();
    } 
    try {
        Log.d(TAG,"Object no." + (i+1) + " field1: " + jsonObj.get("0") + " field2:       " + jsonObj.get("1"));
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到以下异常:

java.lang.ClassCastException: org.json.simple.JSONArray
// at JSONArray array = (JSONArray)obj;
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?

谢谢.

Lal*_*ani 11

而不是将您的对象转换为JSONArray,您应该这样做:

JSONArray mJsonArray = new JSONArray(jsonString);
JSONObject mJsonObject = new JSONObject();
for (int i = 0; i < mJsonArray.length(); i++) {
    mJsonObject = mJsonArray.getJSONObject(i);
    mJsonObject.getString("0");
    mJsonObject.getString("id");
    mJsonObject.getString("1");
    mJsonObject.getString("name");
}
Run Code Online (Sandbox Code Playgroud)