简体   繁体   中英

JSON-simple ClassCastException from String to JSONObject

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

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM