當前位置:
首頁 > 知識 > 獲取json數據中某一特定鍵值

獲取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");

獲取json數據中某一特定鍵值

打開今日頭條,查看更多圖片
喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序員小新人學習 的精彩文章:

2019年可能大火的編程語言清單已出爐!
使用vue-cli+axios配置代理進行跨域訪問數據

TAG:程序員小新人學習 |