本文将总结介绍一下Json数据的各种解析的思路和方法
1,原生的Json数据的解析思路
拿到一段需要解析的json数据
{
"resultcode":"200",
"reason":"Return Successd!",
"result":{
"province":"浙江",
"city":"杭州",
"areacode":"0571",
"zip":"310000",
"company":"中国移动",
"card":"移动动感地带卡"
}
}
这是一个基本的json数据了,首先一个大括号,里面是键值对,每一个键对应一个值,里面又包含result的一个大括号,相当于嵌套了一次数据,看一下数据格式:
解析代码如下:
private void JsonParse(String jsonString){
if(!TextUtils.isEmpty(jsonString)){
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject jsonObjectResult = jsonObject.getJSONObject("result");
tv_content.setText("归属地:" + jsonObjectResult.getString("province") + "-"
+ jsonObjectResult.getString("city")
+ "\n" + "区号:" + jsonObjectResult.getString("areacode")
+ "\n" + "运营商:" + jsonObjectResult.getString("company")
+ "\n" + "用户类型:" + jsonObjectResult.getString("card"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
很多json数据都是带有数组的,如天气数据,数据就比较复杂一点,一层一层的分析,其实也就是多层数据的嵌套,我们来看一下天气的数据:
{
"resultcode": "200",
"reason": "查询成功!",
"result": {
"sk": { /*当前实况天气*/
"temp": "21", /*当前温度*/
"wind_direction": "西风", /*当前风向*/
"wind_strength": "2级", /*当前风力*/
"humidity": "4%", /*当前湿度*/
"time": "14:25" /*更新时间*/
},
"today": {
"city": "天津",
"date_y": "2014年03月21日",
"week": "星期五",
"temperature": "8℃~20℃", /*今日温度*/
"weather": "晴转霾", /*今日天气*/
"weather_id": { /*天气唯一标识*/
"fa": "00", /*天气标识00:晴*/
"fb": "53" /*天气标识53:霾 如果fa不等于fb,说明是组合天气*/
},
"wind": "西南风微风",
"dressing_index": "较冷", /*穿衣指数*/
"dressing_advice": "建议着大衣、呢外套加毛衣、卫衣等服装。", /*穿衣建议*/
"uv_index": "中等", /*紫外线强度*/
"comfort_index": "",/*舒适度指数*/
"wash_index": "较适宜", /*洗车指数*/
"travel_index": "适宜", /*旅游指数*/
"exercise_index": "较适宜", /*晨练指数*/
"drying_index": ""/*干燥指数*/
},
"future": [ /*未来几天天气*/
{
"temperature": "28℃~36℃",
"weather": "晴转多云",
"weather_id": {
"fa": "00",
"fb": "01"
},
"wind": "南风3-4级",
"week": "星期一",
"date": "20140804"
},
{
"temperature": "28℃~36℃",
"weather": "晴转多云",
"weather_id": {
"fa": "00",
"fb": "01"
},
"wind": "东南风3-4级",
"week": "星期二",
"date": "20140805"
},
{
"temperature": "27℃~35℃",
"weather": "晴转多云",
"weather_id": {
"fa": "00",
"fb": "01"
},
"wind": "东南风3-4级",
"week": "星期三",
"date": "20140806"
},
{
"temperature": "27℃~34℃",
"weather": "多云",
"weather_id": {
"fa": "01",
"fb": "01"
},
"wind": "东南风3-4级",
"week": "星期四",
"date": "20140807"
},
{
"temperature": "27℃~33℃",
"weather": "多云",
"weather_id": {
"fa": "01",
"fb": "01"
},
"wind": "东北风4-5级",
"week": "星期五",
"date": "20140808"
},
{
"temperature": "26℃~33℃",
"weather": "多云",
"weather_id": {
"fa": "01",
"fb": "01"
},
"wind": "北风4-5级",
"week": "星期六",
"date": "20140809"
},
{
"temperature": "26℃~33℃",
"weather": "多云",
"weather_id": {
"fa": "01",
"fb": "01"
},
"wind": "北风4-5级",
"week": "星期日",
"date": "20140810"
}
]
},
"error_code": 0
}
数据比较多,我们用工具看一下数据格式:
通过数据格式,这个Json数据就简单明了,解析代码如下:
private void JsonWeatherParse(String jsonString) {
//清空数据
WeatherList.clear();
if (!TextUtils.isEmpty(jsonString)) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject jsonObjectResult = jsonObject.getJSONObject("result");
JSONObject jsonObjectToday = jsonObjectResult.getJSONObject("today");
String city = jsonObjectToday.getString("city");
String date_y = jsonObjectToday.getString("date_y");
String temperature = jsonObjectToday.getString("temperature");
String weather = jsonObjectToday.getString("weather");
String week = jsonObjectToday.getString("week");
tv_content.setText("城市:" + city
+ "\n" + "日期:" + date_y
+ "\n" + "星期:" + week
+ "\n" + "温度:" + temperature
+ "\n" + "天气:" + weather);
//解析数组格式
JSONArray jsonArrayFuture = jsonObjectResult.getJSONArray("future");
//遍历每一个数组的数据
for (int i = 0; i < jsonArrayFuture.length(); i++) {
JSONObject jsonObject01 = (JSONObject) jsonArrayFuture.get(i);
Weather weatherbean = new Weather();
weatherbean.setDate(jsonObject01.getString("date"));
weatherbean.setTemperature(jsonObject01.getString("temperature"));
weatherbean.setWeather(jsonObject01.getString("weather"));
weatherbean.setWeek(jsonObject01.getString("week"));
weatherbean.setWind(jsonObject01.getString("wind"));
WeatherList.add(weatherbean);
}
tv_content01.setText("日期:" + WeatherList.get(0).getDate()
+ "\n" + "星期:" + WeatherList.get(0).getWeek()
+ "\n" + "温度:" + WeatherList.get(0).getTemperature()
+ "\n" + "天气:" + WeatherList.get(0).getWeather()
+ "\n" + "风向:" + WeatherList.get(0).getWind());
tv_content02.setText("日期:" + WeatherList.get(1).getDate()
+ "\n" + "星期:" + WeatherList.get(1).getWeek()
+ "\n" + "温度:" + WeatherList.get(1).getTemperature()
+ "\n" + "天气:" + WeatherList.get(1).getWeather()
+ "\n" + "风向:" + WeatherList.get(1).getWind());
tv_content03.setText("日期:" + WeatherList.get(2).getDate()
+ "\n" + "星期:" + WeatherList.get(2).getWeek()
+ "\n" + "温度:" + WeatherList.get(2).getTemperature()
+ "\n" + "天气:" + WeatherList.get(2).getWeather()
+ "\n" + "风向:" + WeatherList.get(2).getWind());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
如果碰到数组循环嵌套数值的json数据,方法也一样,仍然是先从数组中拿到JSONObject ,在获取JSONArray 对象,重复一遍工作,以上就是原生的Json解析。
我在第二个解析中用到了一个weather的对象存储数据,但是这样一个一个的获取数据很繁琐,有没有更简单的方式呢,答案当然是有的,就是我们现在比较流行的JSON框架,下面我们就来学习一下。
首先在项目中添加JSON的依赖
compile 'com.google.code.gson:gson:2.7'
GSON库主要是可以讲一段JSON格式的字符串自动的映射成一个对象,从而不需要我们在手动的去编写代码进行解析了。个人觉得难点就在于定义一个对应的类,android Studio也有工具可以根据字符串自动生成对应的类(Gsonformat)有兴趣的同学可以去研究一下他的用法。
我们这里还是以上面的两个json数据来介绍GSON的用法:
定义手机信息的实体类:
public class PhoneBean {
//数据的属性要和json数据的字符保持一直,
//重新命名的需要使用 @SerializedName()进行注解
public String reason;
public String resultcode;
public Result result;
public class Result{
public String areacode;
public String card;
public String city;
public String company;
public String province;
public String zip;
}
}
Gson的使用方法:
private void JsonPhoneParseByGSON(String jsonString){
Gson gson = new Gson();
PhoneBean bean = gson.fromJson(jsonString,PhoneBean.class);//就是这么简单一句话就搞定
//取出数据
tv_content.setText("归属地:" + bean.result.province + "-"
+ bean.result.city
+ "\n" + "区号:" + bean.result.areacode
+ "\n" + "运营商:" + bean.result.company
+ "\n" + "用户类型:" + bean.result.card);
}
下面我们在介绍一下带有数组的json数据用GSON怎么解析:
先看一下实体类的定义:
为了方便理解,我们将多数据的实体类分开定义:
定义今天天气的bean:
public class TodayBean {
public String city;
public String date_y;
public String dressing_advice;
public String dressing_index;
public String exercise_index;
public String temperature;
public String travel_index;
public String uv_index;
public String wash_index;
public String weather;
public String week;
public String wind;
public Weather_id weather_id;
public class Weather_id{
public String fa;
public String fb;
}
}
定义SK,当前信息的bean
public class Skbean {
public String humidity;
public String temp;
public String time;
public String wind_direction;
public String wind_strength;
}
定义一周天气,每一天的数据的bean
public class WeekWeatherBean {
public String date;
public String temperature;
public String weather;
@SerializedName("week")
public String week_week;
@SerializedName("wind")
public String week_wind;
@SerializedName("weather_id")
public Week_Weather_id week_weather_id;
public class Week_Weather_id{
@SerializedName("fa")
public String week_fa;
@SerializedName("fb")
public String week_fb;
}
}
定义前面三个基础类后我们定义一个总类,将基础类包含进去:
public class ResultBean {
public TodayBean today;
public Skbean sk;
public List<WeekWeatherBean> future;//每周的天气是一个数组,多以这里是一个list数据。
}
解析的代码如下:
private void JsonWeatherParseByGSON(String jsonString){
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(jsonString);
String weatherContent = jsonObject.getJSONObject("result").toString();
Log.i("Json","weatherContent=="+weatherContent);
ResultBean bean = new Gson().fromJson(weatherContent,ResultBean.class);
tv_content.setText("城市:" + bean.today.city
+ "\n" + "日期:" + bean.today.date_y
+ "\n" + "星期:" + bean.today.week
+ "\n" + "温度:" + bean.today.temperature
+ "\n" + "天气:" + bean.today.weather);
tv_content01.setText("日期:" + bean.future.get(0).date
+ "\n" + "星期:" + bean.future.get(0).week_week
+ "\n" + "温度:" + bean.future.get(0).temperature
+ "\n" + "天气:" + bean.future.get(0).weather
+ "\n" + "风向:" + bean.future.get(0).week_wind);
tv_content02.setText("日期:" + bean.future.get(1).date
+ "\n" + "星期:" + bean.future.get(1).week_week
+ "\n" + "温度:" + bean.future.get(1).temperature
+ "\n" + "天气:" + bean.future.get(1).weather
+ "\n" + "风向:" + bean.future.get(1).week_wind);
tv_content03.setText("日期:" + bean.future.get(2).date
+ "\n" + "星期:" + bean.future.get(2).week_week
+ "\n" + "温度:" + bean.future.get(2).temperature
+ "\n" + "天气:" + bean.future.get(2).weather
+ "\n" + "风向:" + bean.future.get(2).week_wind);
} catch (JSONException e) {
e.printStackTrace();
}
}
多数据解析时,一行代码就搞定,代码的阅读性也更强了。
需要注意的是:定时的类的属性一定要与json数据的key一致,有些不适合做属性的key需要用@SerializedName(“key”)方法进行标注。
Gson解析就先介绍到这里,希望对各位小伙伴有帮助。