Reputation: 868
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 ?
Upvotes: 0
Views: 260
Reputation: 868
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!
Upvotes: 1
Reputation: 18022
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.
Upvotes: 1