android和服務器進行交互的時候往往會有數據的傳輸,而數據中有一種類型就是Json型,這兩天在研究API接口的問題,服務器返回的數據類型都是Json型的。例如:
1.接收到的json字符串分為兩種一種為array型,一種為Object型。下面就是Object型(嵌套型):
{"errNum":0,"errMsg":"success","retData":{"city":"\u5317\u4eac","pinyin":"beijing","citycode":"101010100","date":"15-07-21","time":"11:00","postCode":"100000","longitude":116.391,"latitude":39.904,"altitude":"33","weather":"\u96f7\u9635\u96e8","temp":"28","l_tmp":"22","h_tmp":"28","WD":"\u65e0\u6301\u7eed\u98ce\u5411","WS":"\u5fae\u98ce(<10m\/h)","sunrise":"05:02","sunset":"19:38"}}
2.提取其中的value值:
(代碼已測試)
String response = (String) msg.obj; // Json字符串解析 String errMsg = null; int errNum = 2; try { JSONObject jsonObject = new JSONObject(response.toString()); errMsg = jsonObject.getString("errMsg"); errNum = jsonObject.getInt("errNum"); } catch (JSONException e1) { // TODO 自動生成的 catch 塊 e1.printStackTrace(); } JSONObject jsonObject1 = null; try { jsonObject1 = new JSONObject(response.toString()) .getJSONObject("retData"); } catch (JSONException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); } String city = null; String date = null; String time = null; String weather = null; String temp = null; String l_tmp = null; String h_tmp = null; String WD = null; String WS = null; String sunrise = null; String sunset = null; try { city = jsonObject1.getString("city"); date = jsonObject1.getString("date"); time = jsonObject1.getString("time"); weather = jsonObject1.getString("weather"); temp = jsonObject1.getString("temp"); l_tmp = jsonObject1.getString("l_tmp"); h_tmp = jsonObject1.getString("h_tmp"); WD = jsonObject1.getString("WD"); WS = jsonObject1.getString("WS"); sunrise = jsonObject1.getString("sunrise"); sunset = jsonObject1.getString("sunset"); } catch (JSONException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); }