我设法从网址中检索Json内容:http://twitter.com/statuses/public_timeline.json 哪个只提供推文。现在我想从另一个URL中检索另一个JSON数组,该URL具有以下格式:
{
"contacts": [
{
"id": "c200",
"name": "Ravi Tamada",
"email": "ravi@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
},
{
"id": "c201",
"name": "Johnny Depp",
"email": "johnny_depp@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
},
.
.
}
您可以验证的差异是一个JSON数组有一个名称而第二个没有。我用于推文检索的代码如下:
private class LoadListTask extends AsyncTask<Void, Tweet, Void> {
private final ProgressDialog pd = new ProgressDialog(TweetTestActivity.this);
// can use UI thread here
@SuppressWarnings("unchecked")
protected void onPreExecute() {
((ArrayAdapter<String>)getListAdapter()).clear();
this.pd.setMessage("Loading List...");
this.pd.show();
}
protected Void doInBackground(Void... ars) {
// TODO 4 new activity with custom adapter to show schedules
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://twitter.com/statuses/public_timeline.json");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
JSONArray ja = new JSONArray(client.execute(get, responseHandler));
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
publishProgress(new Tweet(jo.getString("id_str"),jo.getString("text")));
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@SuppressWarnings("unchecked")
protected void onProgressUpdate(Tweet... progress) {
((ArrayAdapter<Tweet>)getListAdapter()).add(progress[0]);
}
protected void onPostExecute(Void result) {
pd.dismiss();
}
}
问题:我应该执行哪些更改来检索contacts数组?因为当我只是将id_str更改为性别(以及当然的URL)时,我会收到一个错误,其中包含:org.json.JSONException:没有性别值。
答案 0 :(得分:1)
JSONObject jObj = new JSONObject (client.execute(get, responseHandler));
JSONArray ja = new JSONArray(jObj.getJSONArray("contacts"));
enter code here
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
publishProgress(new Tweet(jo.getString("id_str"),jo.getString("text")));
}
并且没有像文字这样的字符串,而您正在阅读---> jo.getString("text");
为什么?
答案 1 :(得分:0)
使用json api真棒。但是考虑对象映射器就像gson http://code.google.com/p/google-gson/或jackson http://jackson.codehaus.org/。他们可能会保持您的代码简洁。