I want to get an json object from this string coming from this JSON file:
{
"categories": {
"category": [
{
"label": "Collaboration",
"thumbnail": "http://mywebite.com/dfsv",
"description": "...",
"contents": {
"@attributes": {
"count": "79"
}
},
"@attributes": {
"id": "ZSQYN2"
}
},
{
"label": "Communication",
"thumbnail": "http://mywebite.com/dfsv",
"description": "...",
"contents": {
"@attributes": {
"count": "43"
}
},
"@attributes": {
"id": "uGQ9MC"
}
}
],
"@attributes": {
"page": "12",
"limit": "0",
"count": "111",
"lang": "en"
}
}
}
I'm using this code :
JSONObject obj = new JSONObject(myString);
And I got this error message:
Value ... of type org.json.JSONArray cannot be converted to JSONObject
And if I do :
JSONArray obj = new JSONArray(myString);
I got this error message:
Value ... of type org.json.JSONObject cannot be converted to JSONArray
...
Do you have any idea ?
-
Are you sure myString is identical in both cases?Ivo– Ivo2014年04月17日 13:38:08 +00:00Commented Apr 17, 2014 at 13:38
-
Yes it's the same stringcooow– cooow2014年04月17日 14:25:02 +00:00Commented Apr 17, 2014 at 14:25
2 Answers 2
JSONArray and JSONObject are two different things, and should not be type compatible with one another, so these errors make sense. This is a JSONArray:
["foo", "bar", "baz"]
This is a JSONObject:
{ "foo" : "bar", "baz" : "quux" }
You may be looking for JSONElement, which in APIs like Google's GSON is the common superclass between both arrays and objects.
Under the Android JSON API they're also not type compatible.
Comments
I've finally found a solution!
I replaced
JSONObject obj = new JSONObject(myString);
by :
JSONObject obj = new JSONObject(myString.substring(myString.indexOf("{"), myString.lastIndexOf("}") + 1));
Answer found here
Hope it will help someone!