解析json数据

解析从服务器返回的json数据
这阵子在做一个天气预报的demo,使用百度天气的api获取json数据进行解析。json数据如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
{
"error": 0,
"status": "success",
"date": "2015-10-01",
"results": [
{
"currentCity": "nanjing",
"pm25": "76",
"index": [
{
"title": "穿衣",
"zs": "舒适",
"tipt": "穿衣指数",
"des": "建议着长袖T恤、衬衫加单裤等服装。年老体弱者宜着针织长袖衬衫、马甲和长裤。"
},
{
"title": "洗车",
"zs": "较不宜",
"tipt": "洗车指数",
"des": "较不宜洗车,未来一天无雨,风力较大,如果执意擦洗汽车,要做好蒙上污垢的心理准备。"
},
{
"title": "旅游",
"zs": "适宜",
"tipt": "旅游指数",
"des": "天气较好,温度适宜,是个好天气哦。这样的天气适宜旅游,您可以尽情地享受大自然的风光。"
},
{
"title": "感冒",
"zs": "较易发",
"tipt": "感冒指数",
"des": "昼夜温差较大,较易发生感冒,请适当增减衣服。体质较弱的朋友请注意防护。"
},
{
"title": "运动",
"zs": "适宜",
"tipt": "运动指数",
"des": "天气较好,赶快投身大自然参与户外运动,尽情感受运动的快乐吧。"
},
{
"title": "紫外线强度",
"zs": "中等",
"tipt": "紫外线强度指数",
"des": "属中等强度紫外线辐射天气,外出时建议涂擦SPF高于15、PA+的防晒护肤品,戴帽子、太阳镜。"
}
],
"weather_data": [
{
"date": "周四 10月01日 (实时:15℃)",
"dayPictureUrl": "http://api.map.baidu.com/images/weather/day/duoyun.png",
"nightPictureUrl": "http://api.map.baidu.com/images/weather/night/duoyun.png",
"weather": "多云",
"wind": "西北风4-5级",
"temperature": "23 ~ 14℃"
},
{
"date": "周五",
"dayPictureUrl": "http://api.map.baidu.com/images/weather/day/qing.png",
"nightPictureUrl": "http://api.map.baidu.com/images/weather/night/qing.png",
"weather": "晴",
"wind": "东南风微风",
"temperature": "24 ~ 14℃"
},
{
"date": "周六",
"dayPictureUrl": "http://api.map.baidu.com/images/weather/day/duoyun.png",
"nightPictureUrl": "http://api.map.baidu.com/images/weather/night/duoyun.png",
"weather": "多云",
"wind": "东风微风",
"temperature": "24 ~ 17℃"
},
{
"date": "周日",
"dayPictureUrl": "http://api.map.baidu.com/images/weather/day/yin.png",
"nightPictureUrl": "http://api.map.baidu.com/images/weather/night/yin.png",
"weather": "阴",
"wind": "东风3-4级",
"temperature": "24 ~ 19℃"
}
]
}
]
}

发送请求

网络请求需要在非主线程中使用,避免拥塞

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public void getWeatherInfo()
{
new Thread(new Runnable() {
@Override
public void run()
{
try
{
HttpClient httpClient = new DefaultHttpClient();
location = "南京";
url = "http://api.map.baidu.com/telematics/v3/weather?location="+location+"&output=json&ak=gVdU1hNhSplDXKmdLtoRvK0O";
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode()==200)
{
Log.d(TAG,"服务器返回的代码为 "+httpResponse.getStatusLine().getStatusCode());
Log.d(TAG,"获取json成功");
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity, "UTF-8");

//调用解析
Log.d(TAG,"获取到的数据 "+response);
//创建对象调用解析方法
ParseJson parseJson = new ParseJson();
parseJson.parseJsonWithGson(response);
parseJson.parseJson(response);
}
}
catch (Exception e)
{e.printStackTrace();}

}
}).start();
}

解析数据

使用原生

先获取三个对象,error、status和date
再通过数组遍历results中的对象,以此类推将数组中的所有数据取出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public void parseJson(String jsonData)
{
try
{
Log.d(TAG,"解析json数据");
JSONObject jsonObject = new JSONObject(jsonData);
Log.d(TAG,"error is "+jsonObject.get("error"));
Log.d(TAG,"status is "+jsonObject.get("status"));
Log.d(TAG,"date is "+jsonObject.get("date"));
//找到今天的日期
String strGetDate = jsonObject.get("date").toString();
String regExGetDate = "(\\d{4})-(\\d{2})-(\\d{2})";
Pattern patternGetDate = Pattern.compile(regExGetDate);
Matcher matcherGetDate = patternGetDate.matcher(strGetDate);
boolean isFindDate = matcherGetDate.find();
final String date = matcherGetDate.group();
Log.d(TAG,"是否找到日期 "+isFindDate);
Log.d(TAG,"今天日期是 "+date);

JSONArray resultsJsonArray = jsonObject.getJSONArray("results");//遍历results
for (int i = 0;i<resultsJsonArray.length();i++)
{
org.json.JSONObject jsonObjectInResults = resultsJsonArray.getJSONObject(i);
Log.d(TAG,"pm25 is "+jsonObjectInResults.get("pm25"));

String currentCity = jsonObjectInResults.get("currentCity").toString();
Log.d(TAG,"currentCity is "+currentCity);
}
}catch (Exception e)
{
e.printStackTrace();
}
}

使用Gson

Gson 是Google 的一个解析json的库,使用起来比 org.json.JSONArray 和 org.json.JSONObject 简便一些

首先需要定义一个类

类中的成员变量必须和json中的 key 是一样的,变量类型也要相互对应

  • 解析单个对象
1
2
3
4
{
"name": "PPTing",
"age": 21,
}

对应的类应该这么定义

1
2
3
4
5
public class Person
{
public String name;
public int age;
}
  • 解析嵌套对象
1
2
3
4
5
6
7
8
{
"name":"PPTing",
"age":21,
"other":{
"email":"i@ppting.me",
"location":"nanjing"
}
}

对应的类应该这么定义

1
2
3
4
5
6
7
8
9
10
11
public class Person
{
public String name;
public int age;
public Other other;
public static class Other
{
public String email;
public String location;
}
}
  • 解析数组
1
2
3
4
5
6
7
8
{
"name": "PPTing",
"age": 21,
"results":[
"email":"i@ppting.me",
"location":"nanjing"
]
}

对应的类应该这么定义

1
2
3
4
5
6
7
8
9
10
11
public class Person
{
public String name;
public int age;
public List<Results> results = new ArrayList<Results>();
public static class Results
{
public String email;
public String location;
}
}

然后再在类中加入setget方法 在Android Studio 中添加set 和 get 方法的快捷键是 command + N

####开始解析

1
2
3
4
5
6
7
public void parseJsonWithGson(String jsonData)
{
Log.d(TAG,"用gson进行解析");
Gson gson = new Gson();
Person person = gson.fromJson(jsonData,Person.class);
Log.d(TAG,"email is "+person.getEmail());
}

这样就可以获取到email 的值

这里贴上用来解析文章开头的天气json的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package me.ppting.weather;

import android.util.Log;

import java.util.ArrayList;
import java.util.List;

/**
* Created by PPTing on 15/9/22.
*/
public class WeatherInfo
{
private String error;
private String status;
private String date;
public String getError() {return error;}
public void setError(String error) {this.error = error;}
public String getStatus() {return status;}
public void setStatus(String status) {this.status = status;}
public String getDate(){return date;}
public void setDate(String date){this.date = date;}


public List<Results> results = new ArrayList<Results>();
public List<Results> getResults(){return results;}
public void setresults(List<Results> results){this.results = results;}
public static class Results
{
public String currentCity;
public String pm25;

public List<Index> getIndex() {
return index;
}

public void setIndex(List<Index> index) {
this.index = index;
}

public List<Index> index = new ArrayList<Index>();

public List<Weather_data> getWeather_data() {
return weather_data;
}

public void setWeather_data(List<Weather_data> weather_data) {
this.weather_data = weather_data;
}

private List<Weather_data> weather_data = new ArrayList<Weather_data>();
//get and set
public String getCurrentCity(){return currentCity;}
public void setCurrentCity(String currentCity){this.currentCity = currentCity;}
public String getPm25(){return pm25;}
public void setPm25(String pm25){this.pm25 = pm25;}
public static class Index
{
private String title;
private String zs;
private String des;
private String tipt;

public String getTitle(){return title;}
public void setTitle(String title){this.title = title;}
public String getZs(){return zs;}
public void setZs(String zs){this.zs = zs;}
public String getTipt() {return tipt;}
public void setTipt(String tipt) {this.tipt = tipt;}
public String getDes() {return des;}
public void setDes(String des) {this.des = des;}

}
public class Weather_data
{
private String data;
private String dayPictureUrl;
private String nightPictureUrl;
private String weather;
private String wind;
private String temperature;

public String getData() {
return data;
}

public void setData(String data) {
this.data = data;
}

public String getDayPictureUrl() {
return dayPictureUrl;
}

public void setDayPictureUrl(String dayPictureUrl) {
this.dayPictureUrl = dayPictureUrl;
}

public String getNightPictureUrl() {
return nightPictureUrl;
}

public void setNightPictureUrl(String nightPictureUrl) {
this.nightPictureUrl = nightPictureUrl;
}
public String getWeather() {return weather;}
public void setWeather(String weather) {
this.weather = weather;
}
public String getWind() {
return wind;
}
public void setWind(String wind) {
this.wind = wind;
}
public String getTemperature() {
return temperature;
}
public void setTemperature(String temperature) {
this.temperature = temperature;
}
}
}
}

参考:
Stackoverflow

Android gson
通过Gson解析Json数据
Android中使用Gson解析稍复杂的JSON数据

这里有两个小工具:

Tips:
[]: 定义成一个List
{}: 定义成一个类

作者

PPTing

发布于

2015-10-02

更新于

2022-02-12

许可协议

评论