Gson入门教程,json定义一个JavaBean类Person:
package ccc.json;
public class Person {
Integer id;
String name;
String place;
public Person(Integer id, String name, String place) {
super();
this.id = id;
this.name = name;
this.place = place;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
@Override
public String toString() {
return "Person [id=" + id + ",, place=" + place + "]";
}
}
再定义一个JsonService用于生成各种形式的对象如Object,List,List<Map<String,Object>>
package ccc.json; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class JsonService { public Person getPerson(){ Person person=new Person(123,"bobo","HangZhou"); return person; } public List<Person> getlistPerson(){ List<Person> list=new ArrayList<Person>(); Person person2 = new Person(2002, "bobo", "HangZhou"); Person person1=new Person(123,"sisi","BeiJing"); list.add(person1); list.add(person2); return list; } public List<String> getlistString(){ List<String> list=new ArrayList<String>(); list.add("BeiJing"); list.add("HangZhou"); return list; } public List<Map<String,Object>> getlistMap(){ List<Map<String,Object>> list=new ArrayList<Map<String,Object>>(); Map<String,Object> map1=new HashMap<String, Object>(); map1.put("id", 123); map1.put("name","sisi"); map1.put("place", "BeiJing"); Map<String,Object> map2=new HashMap<String, Object>(); map2.put("id", 456); map2.put("name","bobo"); map2.put("place", "HangZhou"); list.add(map1); list.add(map2); return list; } }
GsonDemo入口:
package ccc.json; import java.util.List; import java.util.Map; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class Json_demo { main(String[] args) { Gson gson = new Gson(); JsonService service = new JsonService(); String str1 = gson.toJson(service.getPerson()); System.out.println("1: "+str1); String str2 = gson.toJson(service.getlistPerson()); System.out.println("2: "+str2); String str3 = gson.toJson(service.getlistString()); System.out.println("3: "+str3); String str4 = gson.toJson(service.getlistMap()); System.out.println("4: "+str4); //在已经知道要转成List的情况下可以直接带List.class参数 List<Map> list = gson.fromJson(str4 , List.class); for(Map map : list){ String s = gson.toJson(map); Person p =gson.fromJson(s, Person.class); System.out.println(p); } //转泛型的时候会把int转成double List<Map<String,Object>> list_map = gson.fromJson(str4, new TypeToken<List<Map<String,Object>>>(){}.getType()); for(Map m: list_map){ System.err.println(m);; } //转Person可以把double的小数舍去 List<Person> personList = gson.fromJson(str2 , new TypeToken<List<Person>>(){}.getType()); for(Person p: personList){ System.out.println(p); } } }