简体   繁体   中英

ClassCastException Parsing string to JSONArray

I have a JSON string like the one below being returned from a REST app to an Android app:

"{ \"error\" : false , \"volume\" : 1000 }"

I then try to parse out the response with following (not the exact function, but the exact code causing trouble):

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public void jsonFunction(String result){
    JSONArray jsonArr = (JSONArray) new JSONParser().parse(result);
    JSONObject json = (JSONObject) jsonArr.get(0);
}

However, every time I try to parse the JSON string, I get the following error:

java.lang.String cannot be cast to org.json.simple.JSONArray
java.lang.ClassCastException: java.lang.String cannot be cast to org.json.simple.JSONArray

I've used the same code to parse a JSON response from another REST app within the same program, but that one executes without any trouble. If I try to parse directly to a JSONObject, I get a very similar error message. I figure there has to be something I'm not seeing, but for the life of me I can't quite seem to determine what it is.

EDIT:

This is what I get trying to parse directly to a JSON object:

java.lang.String cannot be cast to org.json.simple.JSONObject
java.lang.ClassCastException: java.lang.String cannot be cast to org.json.simple.JSONObject

Your json response is not an array, this is all you need to do.

  import org.json.JSONException;
  import org.json.JSONObject;

  try {
       JSONObject obj = new JSONObject(result);
       boolean error = obj.getBoolean("error");
       int volume = obj.getInt("volume");
  } catch (JSONException e){

  }

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