简体   繁体   中英

Android cannot be converted to JSONObject error

I have a array of JSON objects being returned from a server (as follows),

["{\"schedule\":{\"type\":\"times\"},\"videos\":{\"abc\":\"def\"}}","{\"schedule\":{\"type\":\"tod_repeat\",\"start\":\"00:09:00\"},\"videos\":{\"mk_320059\":{\"url\":\"http://m.mtvkatsomo.fi/?progId=320059\",\"siteId\":\"mk\"}}}"]

which seems to be valid json as per JSONLint ( http://jsonlint.com/ ). However in android when I try to convert this to an object I get an exception,

org.json.JSONException: Value {"schedule":{"type":"times"},"videos":{"abc":"def"}} at 0 of type java.lang.String cannot be converted to JSONObject

The relevant code is,

if (resp != null) {
    try {
        JSONArray lists = new JSONArray(resp);
        Log.d(CLASS_NAME, "STRING REP:"+lists.getJSONObject(0).toString()); // <-- at this line
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

It seems like I am missing something here as I cant seem to figure out what the problem is here. Any help is appreciated.

Root JSONArray contain Strings as item instead of JSONObject so try as to get JSONObject from JSONArray :

     JSONArray lists = new JSONArray(resp);
     for (int i = 0; i < lists.length(); i++) {
         String str_value=  lists.optString(i);
          // get JSONObject from String
          JSONObject jsonobj=new JSONObject(str_value);
       }

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