我正在尝试为YouTube开发一个示例应用程序,以便直接从YouTube上在我的Android设备上播放视频。在这方面我已经开发了一些代码来解析JSON,但到目前为止我还没有成功。请帮帮我,如何解析Youtube JSON? 这是我的代码。
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getVideoJSON ();
}
public JSONObject getVideoJSON ()
{
final String URL = "https://gdata.youtube.com/feeds/api/users/Football/uploads?v=2&alt=json";
try
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray VideoData = new JSONArray(data);
JSONObject video = VideoData.getJSONObject(0);
Log.e("URL", "Successfully parse");
return video;
}
catch(Exception e)
{
Log.e("URL", "Failed");
e.printStackTrace();
}
return null;
}
答案 0 :(得分:1)
这个url会返回给你一个JSONObject,而不是JSONArray,试试这个:
public JSONObject getVideoJSON ()
{
final String URL = "https://gdata.youtube.com/feeds/api/users/Football/uploads?v=2&alt=json";
try
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject VideoData = new JSONObject(data);
Log.e("URL", "Successfully parse");
return video;
}
catch(Exception e)
{
Log.e("URL", "Failed");
e.printStackTrace();
}
return null;
}
如果您想更清楚地看到您的JSON结构,此网站可能会有所帮助:http://json-indent.appspot.com/