Reputation:
I am facing a problem . When i tried to receive the value I am getting error that items of type org.json.JSONArray cannot be converted to JSONObject
. How can i solve this?
JSONObject jsonObject = new JSONObject(response);
JSONObject snippet = jsonObject.getJSONObject("items");
String t = snippet.getString("rating");
Upvotes: 0
Views: 835
Reputation: 3576
[..] means it should be an JSONArray and {..} means it should be a JSONObject.
Do this:
JSONArray snippet = jsonObject.getJSONArray("items");
JSON having a value enclosed within []
signifies an array as is a common practice in most programming languages and {}
as a plain JSON entity.
Hence,
when syntax is {}then this is JSONObject
when syntax is [] then this is JSONArray
Upvotes: 1
Reputation: 5294
A JSONArray
is an array of JSONObject
s. Your items
json node is an array, not an object. Replace
JSONObject snippet = jsonObject.getJSONObject("items");
with
JSONArray snippet = jsonObject.getJSONArray("items");
Then from your snippet array you can get the item object you need
JSONObject item = snippet.getJSONObject(0);
And from there
String t = item.getString("rating");
Upvotes: 0
Reputation: 146
Just change from getJSONObject a getJSONArray for the items attribute.
JSONArray snippet = jsonObject.getJSONArray("items");
Upvotes: 1