您的位置:首页 > 移动开发 > Android开发

Android之Json解析

2016-07-05 01:10 393 查看
JSON返回示例:
{ /*JSONObject*/
    "resultcode": "200",
    "reason": "SUCCESSED!",
    "result": [ /*JSONArray*/
        { /*JSONObject*/
            "city": "苏州",  /*城市*/
            "PM2.5": "73",  /*PM2.5指数*/
            "AQI": "98",    /*空气质量指数*/
            "quality": "良", /*空气质量*/
            "PM10": "50",/*PM10*/
            "CO": "0.79",  /*一氧化碳*/
            "NO2": "65",  /*二氧化氮*/
            "O3": "28",    /*臭氧*/
            "SO2": "41",  /*二氧化硫*/
            "time": "2014-12-26 11:48:40"/*更新时间*/  
        }
    ],
    "error_code": 0
}

实例:JSONDemo
运行效果:



主要代码片段:

protected void onPostExecute(String result) {
if (result != null) {
try {
JSONObject jsonObject = new JSONObject(result);
int resultCode = jsonObject.getInt("resultcode");
if (resultCode == 200) {
JSONArray resultJsonArray = jsonObject.getJSONArray("result");
JSONObject resultJsonObject = resultJsonArray.getJSONObject(0);
String output = context.getString(R.string.city) + ": " + resultJsonObject.getString("city") + "\n"
+ context.getString(R.string.PM25) + ": " + resultJsonObject.getString("PM2.5") + "\n"
+ context.getString(R.string.AQI) + ": " + resultJsonObject.getString("AQI") + "\n"
+ context.getString(R.string.quality) + ": " + resultJsonObject.getString("quality") + "\n"
+ context.getString(R.string.PM10) + ": " + resultJsonObject.getString("PM10") + "\n"
+ context.getString(R.string.CO) + ": " + resultJsonObject.getString("CO") + "\n"
+ context.getString(R.string.NO2) + ": " + resultJsonObject.getString("NO2") + "\n"
+ context.getString(R.string.O3) + ": " + resultJsonObject.getString("O3") + "\n"
+ context.getString(R.string.SO2) + ": " + resultJsonObject.getString("SO2") + "\n"
+ context.getString(R.string.time) + ": " + resultJsonObject.getString("time") + "\n";
tv_result.setText(output);
} else if (resultCode == 202) {
String reason = jsonObject.getString("reason");
tv_result.setText(reason);
} else {
Toast.makeText(context, "查询失败",
Toast.LENGTH_LONG).show();
tv_result.setText("");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Toast.makeText(context, "查询失败",
Toast.LENGTH_LONG).show();
tv_result.setText("");
}
}

分析:key值 'result' 后面对应的是数组,所以上面代码用法是getJSONArray; 数组当中又是一个{ }对象,所以代码中就是 resultJsonArray.getJSONObject(0);  这句 。 总而言之记住一个原则,value是什么类型,那么就用什么类型去获取。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android json