Search code examples
javajsontastypie

JSON format error with tastypie JSON result


I have a problem with a Tastypie/Django JSON response in my Java Android code. I do GET http method to an Tastypie API and I parse the httpresponse to JSON. The problem it's that when I create a JSONArray with the json response, this throw an exception .

JSONTokener tokener = new JSONTokener(json);
finalResult = new JSONArray(json);

I get the next error message:

System.err(27193): org.json.JSONException: Value {"objects 
[{"id":"1","resource_uri":"\/api\/v1\/user\/1\/","od_user":"Usuario administrador del 
sitio","nick":"Admin","reg_date":"2012-08-07T15:39:20.706060+00:00"},
{"id":"2","resource_uri":"\/api\/v1\/user\/2\/","od_user":"user 
test","nick":"test1","reg_date":"2012-08-08T10:44:50+00:00"}],"meta":
{"limit":20,"previous":null,"offset":0,"total_count":2,"next":null}} of type 
org.json.JSONObject cannot be converted to JSONArray
W/System.err(27193):    at org.json.JSON.typeMismatch(JSON.java:111)
W/System.err(27193):    at org.json.JSONArray.<init>(JSONArray.java:91)

The JSON archive that I get from the tastypie API is:

{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 2}, "objects": [{"id": "1", "nick": "Admin", "od_user": "Usuario administrador del sitio", "reg_date": "2012-08-07T15:39:20.706060+00:00", "resource_uri": "/api/v1/user/1/"}, {"id": "2", "nick": "test1", "od_user": "user test", "reg_date": "2012-08-08T10:44:50+00:00", "resource_uri": "/api/v1/user/2/"}]}

I don't know why tastypie API JSON format can't be parsing to JSONArray.


Solution

  • That's because your JSON is a JSON Object and not an array. You can parse your JSON until you get to objects value and then try to convert that into a JSON array.

    A JSON Array always looks like:

    '[1, 2, 3, 4]'
    

    Please note that [] is the enclosure needed for a JSON string to represent a JSON array.