开发者

Parsing JSON from YouTube API

开发者 https://www.devze.com 2023-04-11 06:05 出处:网络
I have a URL: https://gdata.youtube.com/feeds/api/users/charlieissocoollike/uploads?alt=jsonc&v=2which supplies JSON information on latest youtube uploads from a user.

I have a URL: https://gdata.youtube.com/feeds/api/users/charlieissocoollike/uploads?alt=jsonc&v=2 which supplies JSON information on latest youtube uploads from a user.

I have written some code to parse this JSON data but I don't understand how JSON works and how to parse it in 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;           
}

How should I pull the video id, title and description from the JSON Data of each video object?


In http://www.json.org/ has a parser implemented in JAVA.


You're almost there. What you need is:

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

Then you can traverse over each video:

for (int i = 0; i < items.length(); i++) {
    JSONObject videoObject = items.getJSONObject(i); 
    String title = videoObject.getString("title");
    String videoId = videoObject.getString("id");
}


You'd be better off using the official client library: http://code.google.com/apis/youtube/2.0/developers_guide_java.html#Retrieving_user_activity_feeds

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号