Using Java to decode JSON array of objects

Jake picture Jake · Nov 25, 2011 · Viewed 12.9k times · Source

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.

Answer

Lalit Poptani picture Lalit Poptani · Nov 25, 2011

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