【发布时间】:2016-08-23 05:18:44
【问题描述】:
所以我使用 asynctask 来访问在线托管的 json 文件。我能够在我的 Android 应用程序中显示 json。现在我想显示 json 文件中的某些值。下面是我用过的json文件。
https://feeds.citibikenyc.com/stations/stations.json
例如,假设我只想显示这个 json 中的 id。我该怎么做?
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
}
这里我在'result'中得到了完整的json值
PS:完成异步任务
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(GetJson.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null; //BufferedReader reads text from the input stream
try {
URL url = new URL(params[0]); // params[0] is the first value in String..params (String..params can
//have any no.of string parameters )
connection = (HttpURLConnection) url.openConnection();
connection.connect(); //not necessary.works without this.
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer(); // A string buffer is like a String, but can be modified
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
//Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
//Log.d("BufferTest",buffer.toString());
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String result) { //Here the 'result' is whatever that is returned from the
//doinbackground method (Ex: buffer.toString(); )
try {
JSONObject jsonobject = new JSONObject(result);
JSONArray jsonarray = jsonobject.getJSONArray("stationBeanList");
String id = "";
for(int i =0; i<jsonarray.length();i++){
JSONObject jsonObject2 = jsonarray.getJSONObject(i);
id = jsonObject2.getString("stationName");
txtJson.setText(id);
}
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
//txtJson.setText(result);
}
}
【问题讨论】:
-
遍历
stationBeanList数组并从每个jsonObject获取id。 -
你应该看看
JSONObject。 -
在下面看到我的答案
标签: android json android-asynctask