获取json数据中某一特定键值

上一篇博文,我们介绍了如何将真个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");

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值