3

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
  • You get that error on what line??? Commented Nov 25, 2011 at 4:09

1 Answer 1

12

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");
}
Sign up to request clarification or add additional context in comments.

5 Comments

I am surprised this answer worked for you because there is no JSONArray constructor that takes a string!
@GeekStocks here it is
@Lalit - that's a different class, I am using org.json.simple.JSONArray and the link you gave is org.json.JSONArray so that is the difference...
@GeekStocks ok but I gave answer considering org.json.JSONArray!
@Lalit - yes that is the difference. There are actually several other packages containing JSONArray classes and this is leading to confusion.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.