解析工具类: import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.domain.Student; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class GsonParserUtils { // 谷歌Gson,生成JSON字符串和解析JSON工具类 // Gson将获取的对象生成JSON字符串 public static String toJsonString(Object obj) { Gson gson = new Gson(); // Object是你自己定义的实体对象类 String str = gson.toJson(obj); return str; } /* * //GSON使用泛型将JSON字符串转换回实体类对象(javabean) //JSON中只有一个对象的采用这种解析 */public static <T> T getStudent(String jsonString, Class<T> clazz) { Gson gson = new Gson(); T t = null; t = gson.fromJson(jsonString, clazz); return t; } // JSON有多个对象时采用这种解析(注意:不包括map类的) public static <T> List<T> getStudents(String jsonString,Class<T> clazz) { Gson gson = new Gson(); List<T> list = new ArrayList<T>(); Type type = new TypeToken<List<T>>(){}.getType(); list = gson.fromJson(jsonString,type ); return list; } // JSON是字符串数组时用这种解析,注意这里是不用传入对象 public static <T> List<T> getListString(String jsonString) { Gson gson = new Gson(); List<T> list = new ArrayList<T>(); list = gson.fromJson(jsonString, new TypeToken<List<T>>() { }.getType()); return list; } // JSON如果是Map对象采用这种解析 public static List<Map<String, Object>> getListMap(String jsonStirng) { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); Gson gson = new Gson(); list = gson.fromJson(jsonStirng, new TypeToken<List<Map<String, Object>>>() { }.getType()); return list; } } 实体类Service类:生成对象 import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; //此类用来创建Student对象的工具类,用来进行谷歌GSON解析的工具类 public class StudentService { // 生成一个Student对象 public static Student createStudent() { Student student = new Student(111, 22, "张三"); return student; } // 生成多个Student对象 public static List<Student> createLsitStudent() { Student student = new Student(111, 22, "张三"); Student student2 = new Student(112, 20, "李四"); List<Student> list = new ArrayList<Student>(); list.add(student); list.add(student2); return list; } // 生成字符串数组对象 public static List<String> createListString() { List<String> list = new ArrayList<String>(); list.add("嘿嘿嘿"); list.add("playboy"); return list; } // 生成Map-Student对象 public static List<Map<String, Object>> createListMap() { // List<Map<Integer, Object>>list=new ArrayList<Map<Integer, Object>>(); List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); Map<String, Object> map = new HashMap<String, Object>(); map.put("id", 111); map.put("age", 22); map.put("name", "张三"); /*Student stu=new Student(111,22,"张三"); map.put("1",stu);*/ Map<String, Object> map2 = new HashMap<String, Object>(); map2.put("id", 112); map2.put("age", 20); map2.put("name", "李四"); list.add(map); list.add(map2); return list; /*Student stu2=new Student(112,20,"李四"); map.put("2",stu2); return list;*/ } }