Gson封装
- Gson封装的工具类
- javabean和集合相互转换
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
|
import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken;
import java.util.ArrayList; import java.util.List; import java.util.Map;
public class GsonUtil { private static Gson gson = null;
static { if (gson == null) { gson = new Gson(); } }
private GsonUtil() { }
public static String GsonString(Object object) { String gsonString = null; if (gson != null) { gsonString = gson.toJson(object); } return gsonString; }
public static <T> T GsonToBean(String gsonString, Class<T> cls) { T t = null; if (gson != null) { t = gson.fromJson(gsonString, cls); } return t; }
public static <T> List<T> GsonToList(String gsonString, Class<T> cls) { List<T> list = null; if (gson != null) { list = gson.fromJson(gsonString, new TypeToken<List<T>>() { }.getType()); } return list; }
public static <T> List<T> jsonToList(String json, Class<T> cls) { Gson gson = new Gson(); List<T> list = new ArrayList<T>(); JsonArray array = new JsonParser().parse(json).getAsJsonArray(); for (final JsonElement elem : array) { list.add(gson.fromJson(elem, cls)); } return list; }
public static <T> List<Map<String, T>> GsonToListMaps(String gsonString) { List<Map<String, T>> list = null; if (gson != null) { list = gson.fromJson(gsonString, new TypeToken<List<Map<String, T>>>() { }.getType()); } return list; }
public static <T> Map<String, T> GsonToMaps(String gsonString) { Map<String, T> map = null; if (gson != null) { map = gson.fromJson(gsonString, new TypeToken<Map<String, T>>() { }.getType()); } return map; } }
|