java - 使用 Java 解码对象的 JSON 数组

标签 java android json json-simple

我有如下 JSON:

[{"0":"1","id":"1","1":"abc","name":"abc"},{"0":"2","id":"2","1":"xyz","name":"xyz"}]

它是一个对象数组。

我需要使用 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();
    }
}

我收到以下异常:

java.lang.ClassCastException: org.json.simple.JSONArray
// at JSONArray array = (JSONArray)obj;

有人可以帮忙吗?

谢谢。

最佳答案

不要将您的对象转换为 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");
}

关于java - 使用 Java 解码对象的 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8264725/

相关文章:

android - 单击时从列表中获取单个整数

php - angularjs 4 : how to post raw JSON data

c# - WP7 Json 序列化器不处理 "space"?

json - 如何比较不同顺序的JSON?

java - 实例和类语法

java - Java 中静态变量的延迟初始化 - 执行?

java - 异步启动 Activity 不出现

android - Android 中的 Paint 和 TextPaint 有什么区别?

java - 如何在java程序中识别图像颜色?

android - Android 12 keystore 用户 0 丢失文件夹