我有一个URL: https://gdata.youtube.com/feeds/api/users/charlieissocoollike/uploads?alt=jsonc&v=2,它提供来自用户的最新youtube上传的JSON信息。
我写了一些代码来解析这个JSON数据,但我不明白JSON是如何工作的,以及如何在Java中解析它。
public void getVideoData() throws ClientProtocolException, JSONException, IOException {
JSONObject object = (JSONObject) new JSONTokener(getVideoJSON().toString()).nextValue();
//String query = object.getString("data");
JSONArray locations = object.getJSONArray("data");
output.setText(locations.getString(1));
}
public JSONObject getVideoJSON () throws ClientProtocolException, IOException, JSONException {
final String URL = "https://gdata.youtube.com/feeds/api/users/charlieissocoollike/uploads?alt=jsonc&v=2";
StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray VideoData = new JSONArray(data);
JSONObject video = VideoData.getJSONObject(0);
return video;
}
如何从每个视频对象的JSON数据中提取视频id,标题和描述?
In http://www.json.org/有一个用JAVA实现的解析器
你就快成功了。你需要的是:
JSONObject json = new JSONObject(data);
JSONObject dataObject = json.getJSONObject("data"); // this is the "data": { } part
JSONArray items = dataObject.getJSONArray("items"); // this is the "items: [ ] part
然后你可以遍历每个视频:
for (int i = 0; i < items.length(); i++) {
JSONObject videoObject = items.getJSONObject(i);
String title = videoObject.getString("title");
String videoId = videoObject.getString("id");
}
您最好使用官方客户端库:http://code.google.com/apis/youtube/2.0/developers_guide_java.html#Retrieving_user_activity_feeds