Gson

1.简单的处理list和map

Gson gson = new Gson();
List testList = new ArrayList();
testList.add("first");
testList.add("second");
String listToJson = gson.toJson(testList);
System.out.println(listToJson);		
//prints ["first","second"]

Map testMap = new HashMap();
testMap.put("id", "id.first");
testMap.put("name","name.second");
String mapToJson = gson.toJson(testMap);
System.out.println(mapToJson);	
//prints {"id":"id.first","name":"name.second"}

 2.处理带泛型的集合

List<TestBean> testBeanList = new ArrayList<TestBean>();
TestBean testBean = new TestBean();
testBean.setId("id");
testBean.setName("name");
testBeanList.add(testBean);
		
java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<TestBean>>() {
}.getType();
String beanListToJson = gson.toJson(testBeanList,type);
System.out.println(beanListToJson);
//prints [{"id":"id","name":"name"}]
		
List<TestBean> testBeanListFromJson = gson.fromJson(beanListToJson, type);
System.out.println(testBeanListFromJson);
//prints [TestBean@1ea5671[id=id,name=name,birthday=<null>]]

map等其他集合类型同上


你可能感兴趣的:(list,String,HashMap,null)