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

主要解析 两种格式 列表格式 和 map格式

常用的是列表解析,以前不知道解析map,就用json配合gson使用,今天在论坛看到有人问,就试了一下才发现 解析map也很方便,哇喔,又涨姿势了..


  1. public class jsonParse{  
  2.   
  3.           
  4.   
  5. class City{  
  6.   
  7.         int id;  
  8.   
  9.         String name;  
  10.   
  11.         String code;  
  12.   
  13.         String map;  
  14.   
  15. }  
  16.   
  17.           
  18.   
  19.           
  20.   
  21. public static void main(String[] args) {  
  22.   
  23.         //列表/array 数据  
  24.   
  25.                  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'}]";  
  26.   
  27.         Gson gson=new Gson();  
  28.   
  29.         List<City> rs=new ArrayList<City>();  
  30.   
  31.          Type type = new TypeToken<ArrayList<City>>() {}.getType();  
  32.   
  33.           rs=gson.fromJson(str, type);  
  34.   
  35.           for(City o:rs){  
  36.   
  37.                   System.out.println(o.name);  
  38.   
  39.           }  
  40.   
  41.             
  42.   
  43.           //map数据  
  44.   
  45.           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'}}";  
  46.   
  47.           Map<String, City> citys = gson.fromJson(jsonStr, new TypeToken<Map<String, City>>() {}.getType());   
  48.   
  49.           System.out.println(citys.get("1").name+"----------"+citys.get("2").code);  
  50.   
  51. }  
  52.   
  53.   
  54.   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值