1 package utils; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 import com.google.gson.Gson; 6 import com.google.gson.JsonObject; 7 import com.google.gson.reflect.TypeToken; 8 import java.lang.reflect.Type; 9 import bean.User; 10 import net.sf.json.JSONArray; 11 12 public class GsonUtil { 13 14 /** 15 * 将json数据串转换成对象数据 16 * 17 * @param json 18 * @param cls 19 * @return 20 * @throws Exception 21 */ 22 public static <T> T fromJson(String json, Class<T> cls) throws Exception { 23 T obj = null; 24 Gson gson = new Gson(); 25 obj = cls.newInstance(); 26 obj = gson.fromJson(json, cls); 27 return obj; 28 } 29 30 /** 31 * 将对象转化成Json 数据串 32 * 33 * @param obj 34 * @return 35 */ 36 public static String objToJson(Object obj) { 37 return new Gson().toJson(obj); 38 } 39 40 /** 41 * 将List Json数据串转换成List集合 42 * 43 * @param json 44 * @param clas 45 * @return 46 */ 47 public static <T> ArrayList<T> jsonToArrayList(String json, Class<T> cls) { 48 Type type = new TypeToken<ArrayList<JsonObject>>() { 49 }.getType(); 50 ArrayList<JsonObject> jsonObjects = new Gson().fromJson(json, type); 51 52 ArrayList<T> arrayList = new ArrayList<>(); 53 for (JsonObject jsonObject : jsonObjects) { 54 arrayList.add(new Gson().fromJson(jsonObject, cls)); 55 } 56 return arrayList; 57 } 58 59 /** 60 * 将List集合转化成Json数据串 61 * 62 * @param list 63 * @return 64 */ 65 public static String listToJson(Object list) { 66 JSONArray jsonArray = JSONArray.fromObject(list); 67 return jsonArray.toString(); 68 } 69 70 /** 71 * test 72 * 测试 73 * @param args 74 */ 75 public static void main(String[] args) { 76 try { 77 User u1 = new User(); 78 u1.setUid(100000); 79 u1.setAddress("sasassdasd"); 80 u1.setAge(25); 81 u1.setEmail("2515@qq.com"); 82 u1.setName("sai"); 83 String string = objToJson(u1); 84 User u2 = new User(); 85 User u3 = new User(); 86 u3.setUid(100000); 87 u3.setAddress("sasassdasd"); 88 u3.setAge(25); 89 u3.setEmail("25175@qq.com"); 90 u3.setName("sai"); 91 List<User> uList = new ArrayList<User>(); 92 uList.add(u1); 93 uList.add(u3); 94 String s2 = listToJson(uList); 95 96 List<User> uList1 = new ArrayList<User>(); 97 uList1 = jsonToArrayList(s2, User.class); 98 99 for (User user : uList1) { 100 System.out.println(user.toString()); 101 } 102 103 u2 = fromJson(string, User.class); 104 System.out.println(u2.toString()); 105 } catch (Exception e) { 106 // TODO Auto-generated catch block 107 e.printStackTrace(); 108 } 109 } 110 111 }