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.
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).