1.简单的处理list和map Java代码
Gson gson = new Gson();
List testList = new ArrayList();
Gson gson = new Gson();
List testList = new ArrayList();
testList.add("first");
testList.add("second");
String listToJson = gson.toJson(testList);
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);
testMap.put("name","name.second");
String mapToJson = gson.toJson(testMap);
System.out.println(mapToJson);
//prints {"id":"id.first","name":"name.second"}
//prints {"id":"id.first","name":"name.second"}
Gson gson = new Gson();
List testList = new ArrayList();
testList.add("first");
testList.add("second");
String listToJson = gson.toJson(testList);
String listToJson = gson.toJson(testList);
System.out.println(listToJson);
//prints ["first","second"]
2.处理带泛型的集合 Java代码
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);
String beanListToJson = gson.toJson(testBeanList,type);
System.out.println(beanListToJson);
//prints [{"id":"id","name":"name"}]
List<TestBean> testBeanListFromJson = gson.fromJson(beanListToJson, type);
List<TestBean> testBeanListFromJson = gson.fromJson(beanListToJson, type);
System.out.println(testBeanListFromJson);
//prints [TestBean@1ea5671[id=id,name=name,birthday=<null>]]
//prints [TestBean@1ea5671[id=id,name=name,birthday=<null>]]