source.rar
source.rar

Reputation: 8090

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.

Upvotes: 0

Views: 39

Answers (1)

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132992

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);
       }

Upvotes: 2

Related Questions