JSON轉換
阿新 • • 發佈:2017-05-14
view get obj nal hide pan rom type() 技術分享
public class JSONUtils { private static Gson gson = null; static { if (gson == null) { gson = new Gson(); } } private JSONUtils() { } /** * 轉成json * * @param object * @return */ public static String GsonString(Object object) { String gsonStringView Code= null; if (gson != null) { gsonString = gson.toJson(object); } return gsonString; } /** * 轉成bean * * @param gsonString * @param cls * @return */ public static <T> T GsonToBean(String gsonString, Class<T> cls) { T t= null; if (gson != null) { t = gson.fromJson(gsonString, cls); } return t; } /** * 轉成list * 泛型在編譯期類型被擦除導致報錯 * * @param gsonString * @param cls * @return */ 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; } /** * 轉成list * 解決泛型問題 * * @param json * @param cls * @param <T> * @return */ public <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; } /** * 轉成list中有map的 * * @param gsonString * @return */ 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; } /** * 轉成map的 * * @param gsonString * @return */ 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; } }
JSON轉換