gson解析map和list

来源:互联网 发布:养生软件下载排行榜 编辑:程序博客网 时间:2024/06/07 15:26

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import com.google.common.reflect.TypeToken;

import com.google.gson.Gson;

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>();java.lang.reflect.Type type = new TypeToken<ArrayList<City>>() {}.getType(); 

rs=gson.fromJson(str, type); 

for(City o:rs){ String s=o.id+o.code+o.name+o.map; System.out.println(s);

//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("1").code);

}

}

原创粉丝点击