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.
blackpanther
11.5k12 gold badges53 silver badges79 bronze badges
asked Nov 25, 2011 at 4:07
Jake
17k51 gold badges131 silver badges214 bronze badges
-
You get that error on what line???Hot Licks– Hot Licks2011年11月25日 04:09:43 +00:00Commented Nov 25, 2011 at 4:09
1 Answer 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");
}
Warren Sergent
2,5974 gold badges37 silver badges44 bronze badges
answered Nov 25, 2011 at 4:14
Lalit Poptani
67.3k23 gold badges165 silver badges248 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
Geek Stocks
I am surprised this answer worked for you because there is no JSONArray constructor that takes a string!
Lalit Poptani
@GeekStocks here it is
Geek Stocks
@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...
Lalit Poptani
@GeekStocks ok but I gave answer considering
org.json.JSONArray!Geek Stocks
@Lalit - yes that is the difference. There are actually several other packages containing JSONArray classes and this is leading to confusion.
lang-java