Gson解析(List和Map)格式json数据

有时候服务端非得返回比较傻逼的Json

这时候可以用gson解析带有键值对的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
public class jsonParse{



class City{

int id;

String name;

String code;

String map;

}




public static void main(String[] args) {

//列表/array 数据

String str="[{'id': '1','code': 'bj','name': '北京','map': '39.90403, 116.40752599999996'}, {'id': '2','code': 'sz','name': '深圳','map': '22.543099, 114.05786799999998'}, {'id': '9','code': 'sh','name': '上海','map': '31.230393,121.473704'}, {'id': '10','code': 'gz','name': '广州','map': '23.129163,113.26443500000005'}]";

Gson gson=new Gson();

List<City> rs=new ArrayList<City>();

Type type = new TypeToken<ArrayList<City>>() {}.getType();

rs=gson.fromJson(str, type);

for(City o:rs){

System.out.println(o.name);

}



//map数据

String jsonStr="{'1': {'id': '1','code': 'bj','name': '北京','map': '39.90403, 116.40752599999996'},'2': {'id': '2','code': 'sz','name': '深圳','map': '22.543099, 114.05786799999998'},'9': {'id': '9','code': 'sh','name': '上海','map': '31.230393,121.473704'},'10': {'id': '10','code': 'gz','name': '广州','map': '23.129163,113.26443500000005'}}";

Map<String, City> citys = gson.fromJson(jsonStr, new TypeToken<Map<String, City>>() {}.getType());

System.out.println(citys.get("1").name+"----------"+citys.get("2").code);

}



}