我试图解析这个Json响应。出于某种奇怪的原因,它不起作用。请多多包涵 。我真吮吸Json。
Here is the Url am trying to parse:
这是用于解析它的代码:
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
@Override
protected void onPreExecute() {
Toast.makeText(getActivity(), "started", Toast.LENGTH_SHORT).show();
}
@Override
protected String doInBackground(String... arg0) {
String str = "";
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://gdata.youtube.com/feeds/api/videos/iS1g8G_njx8?v=2&alt=jsonc");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONObject myJson = new JSONObject(str);
String grande = myJson.getString("title");
Toast.makeText(getActivity(), ""+grande, Toast.LENGTH_SHORT).show();
} catch ( JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String strFromDoInBg) {
Toast.makeText(getActivity(), "done", Toast.LENGTH_SHORT).show();
}
}
我只需要解析标题和描述。感谢
答案 0 :(得分:2)
它似乎你没有正确解析
使用以下代码更改您的try块
try{
JSONObject myJson = new JSONObject(str);
JSONObject entityObject = myJson.getJSONObject("entity");
// Parsing title
JSONOBject titleObject = entityObject.getJSONObject("title");
String grande = titleObject.getString("$t");
// Do the same for Description as well (Like above two line)
Toast.makeText(getActivity(), ""+grande, Toast.LENGTH_SHORT).show();
} catch ( JSONException e) {
e.printStackTrace();
}
答案 1 :(得分:0)
我认为你的toast信息(在doInBackground中)会出现问题,尝试将其评论然后再检查!
此外,最佳做法是将响应发送到onPostExecute作为参数,然后在onPostExecute中解析Json
答案 2 :(得分:0)
尝试这样,
@Override
protected String doInBackground(String... arg0) {
String str = "";
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://gdata.youtube.com/feeds/api/videos/iS1g8G_njx8?v=2&alt=jsonc");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
@Override
protected void onPostExecute(String result) {
try{
JSONObject myJson = new JSONObject(result);
JSONObject entry = results.getJSONObject("entry");
JSONObject grande = results.getJSONObject("title");
String title = grande.getString("$t");
Toast.makeText(getActivity(), title, Toast.LENGTH_SHORT).show();
} catch ( JSONException e) {
e.printStackTrace();
}
Toast.makeText(getActivity(), "done", Toast.LENGTH_SHORT).show();
}