Using Java to decode JSON array of objects

谁说胖子不能爱 提交于 2019-12-06 10:25:55

问题


I have JSON as follows:

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

It is an array of objects.

I need to parse it using Java. I am using the library at : http://code.google.com/p/json-simple/downloads/list

Example 1 at this link approximates what I require: http://code.google.com/p/json-simple/wiki/DecodingExamples

I have the following code:

/** 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();
    }
}

I am getting the following exception:

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

Can someone please help?

Thanks.


回答1:


Instead of casting your Object to JSONArray, you should do it like this:

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


来源:https://stackoverflow.com/questions/8264725/using-java-to-decode-json-array-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!