반명우
반명우

Reputation: 1

Android parse youtube subscriber using json

{
   "kind": "youtube#channelListResponse",
   "etag": "\"uQc-MPTsstrHkQcRXL3IWLmeNsM/RcyuNr1qwNrdSKCHUL-TlYislxI\"",
   "pageInfo": {
   "totalResults": 1,
   "resultsPerPage": 1
},
"items": [
{
   "kind": "youtube#channel",
   "etag": "\"uQc-MPTsstrHkQcRXL3IWLmeNsM/06AiodZH5j6AmLIkxRzlAs2py9c\"",
   "id": "UCfba9cyRs4aRiKaGi11d2Ig",
   "statistics": {
      "viewCount": "131077848",
      "commentCount": "8",
      "subscriberCount": "222353",
      "hiddenSubscriberCount": false,
      "videoCount": "5185"
    }
  }
 ]
}

This is json that i want to parse. I want to parse viewCount, subscriberCount and videoCount.

JSONObject jsonObject1 = new JSONObject(jsonStr);
                JSONArray jsonArray1 = jsonObject1.getJSONArray("items");
                JSONObject jsonObject2 = jsonArray1.getJSONObject(0);
                JSONArray jsonArray2 = jsonObject2.getJSONArray("statistics");
                JSONObject jsonObject3 = jsonArray2.getJSONObject(0);

I tried like this but it shows error "JSONObject cannot be converted to JSONArray". How can i get contents inside "statistics"?

(Sorry for my bad English)

Upvotes: 0

Views: 45

Answers (3)

Kacper
Kacper

Reputation: 21

statistic starts with {, so it's JSONObject, not JSONArray. You try to getJSONArray("statistic") instead of getJSONObject("statistic")

Try this:

JSONObject jsonObject1 = new JSONObject(json);
JSONArray jsonArray1 = jsonObject1.getJSONArray("items");
JSONObject jsonObject2 = jsonArray1.getJSONObject(0);
JSONObject jsonObject3 = jsonObject2.getJSONObject("statistics");

And to read values, for example for commentCount:

int commentCount = jsonObject3.getInt("commentCount");

Upvotes: 0

user3801721
user3801721

Reputation: 11

Statistics are not JSON array, but JSON object.

Upvotes: 0

CodePlay
CodePlay

Reputation: 2203

"statistics" is a JSONObject instead of a JSONArray, that's where the error comes.

JSONObject jsonObject1 = new JSONObject(jsonStr);
JSONArray jsonArray1 = jsonObject1.getJSONArray("items");
JSONObject jsonObject2 = jsonArray1.getJSONObject(0);
JSONObject jsonObject3 = jsonObject2.getJSONObject("statistics");
String viewCount = jsonObject3.getString("viewCount");
String subscriberCount = jsonObject3.getString("subscriberCount");
String videoCount = jsonObject3.getString("videoCount");

Upvotes: 1

Related Questions