Reputation: 10095
I have an Array of JSON Objects like this:
{"message":"[\"{\\\"name\\\":\\\"lays\\\",\\\"calories\\\":1.0}\",\"{\\\"name\\\":\\\"lays\\\",\\\"calories\\\":0.33248466}\"]"}
I am trying to parse it using this code:
Object object = parser.parse ( message );
JSONArray array = (JSONArray) object;
for(int i=0;i < array.size () ; i++)
{
System.out.println(array.get ( i ));//output; {"name":"lays","calories":1.0}
JSONObject jsonObj = ( JSONObject ) array.get ( i );//ClassCastExceptio
String foodName = ( String ) jsonObj.get ( KEY_NAME );
Float calories = (Float) jsonObj.get ( KEY_CARLORIES );
Nutrinfo info = new Nutrinfo(foodName,calories);
data.add ( info );
}
but I get a ClassCastException on the marked line. This doesn't make sense: array.get() returns an object, which I cast to a JSONObject. Why am I getting this error.
Thanks.
Upvotes: 1
Views: 1459
Reputation: 9
Object object = parser.parse ( message );
if( object instanceof JSONObject ){
// TODO : process with single JSON Object
}
else if( object instanceof JSONArray ){
// TODO : process with JSONArray Object
}
Upvotes: -1
Reputation: 699
You have multiple json objects within the "message" json object. Use this code to retreve the first values (need a loop for all of them). It seems like you may want to rearrange how you are creating your json objects.
Object object = parser.parse ( message );
JSONArray array = (JSONArray) object;
for(int i=0;i < array.size () ; i++)
{
JSONArray jsonArray = ( JSONArray ) array.get ( i );
JSONObject jsonObj = (JSONObject) jsonArray.get(0);
String foodName = jsonObj.getString ( KEY_NAME );
Float calories = jsonObj.getFloat ( KEY_CARLORIES );
Nutrinfo info = new Nutrinfo(foodName,calories);
data.add ( info );
}
Remember when using JSON, each {} set of brackets signifies an individual JSON object. When dealing with multiple objects on the same level, you must first get the JSON Array (like you did for each message).
Upvotes: 2
Reputation: 53694
You have json content embedded within json content. the "outer" object has a key "message"
with a single string value. that string value happens to be serialized json, but the json parser isn't going to handle that for you automatically. you will have to get the message value and parse that a second time. (actually, it's worse than that, you have at least 2 levels of embedded json content).
Upvotes: 0