本文將總結介紹一下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解析就先介紹到這裏,希望對各位小夥伴有幫助。