上一篇博文,我们介绍了如何将真个json数据赋值给一个成员个数相同的类中,但是有时我们并不需要json的所有数据,那么如何获得json中某一特定值呢。首先假如我们要获得如下json数据的“weather”值
{"weatherinfo":{"city":"北京","cityid":"101010100","temp1":"10℃","temp2":"-2℃","weather":"晴","img1":"d0.gif","img2":"n0.gif","ptime":"08:00"}}
首先定义全局变量:JSONObject jsonObject = new JSONObject();
方法封装如下:
//解析单个Json值,用于获取天气状况
public void readJsonGetWeather(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
} else {
Log.e("JSON", "Failed to download file");
}
jsonObject = new JSONObject(stringBuilder.toString()).getJSONObject("weatherinfo");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
调用该方法:
String url_weather="http://youraddress.cn/data/cityinfo/101010100.html";
readJsonGetWeather(url_weather);
使用值:
climate = jsonObject.getString("weather");//使用哪一个键值就输入对应的键值名称
climateTv.setText(climate);
另一种方法是利用上一文中的方法,先获得json数据,然后获得jsonObject,主要代码如下:
调用:
String url_weather = "http://youraddress.cn/data/cityinfo/101010100.html";
String onlyWeatherResult = connServerForResult(url_weather);//调用上文中的connServerForResult函数,获得json数据。
//具体函数参见上一篇博文
readJsonGetWeather(onlyWeatherResult);
其中readJsonGetWeather函数可精简为:
// 解析单个Json值,用于获取天气状况
public void readJsonGetWeather(String jsonString) {
try {
jsonObject = new JSONObject(jsonString.toString()).getJSONObject("weatherinfo");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
引用的方法是一样的:climate = jsonObject.getString("weather");