您的位置:首页 > 移动开发 > Objective-C

[Android]JsonObject解析

2015-07-22 12:34 489 查看
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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: