主要解析 两种格式 列表格式 和 map格式
常用的是列表解析,以前不知道解析map,就用json配合gson使用,今天在论坛看到有人问,就试了一下才发现 解析map也很方便,哇喔,又涨姿势了..
- 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);
- }
- }