2017-03-07 55 views
0
{ 
    "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" 
    } 
    } 
] 
} 

这是我想解析的json。 我想解析viewCount,subscriberCount和videoCount。Android使用json解析youtube用户

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); 

我试过这样,但它显示错误“JSONObject不能转换为JSONArray”。 我如何获得“统计”内的内容?

(对不起,我英文不好)

回答

1

“统计”是一个JSONObject,而不是一个JSONArray,这就是错误来。

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"); 
0

统计信息不是JSON数组,而是JSON对象。

0

statistic{开头,因此它是JSONObject而不是JSONArray。 您尝试getJSONArray("statistic")而不是getJSONObject("statistic")

试试这个:

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

,并读取数值,例如用于commentCount

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