解析工具類: 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;*/ } }