/** * Gson轉換工具類 */ public class GsonUtils { /** * @param jsonString * json字符串 * @param cls * 要轉換的類 * @param <T> * 返回要轉換的類 * @return */ public static <T> T getPerson(String jsonString, Class<T> cls) { T t = null; try { Gson gson = new Gson(); t = gson.fromJson(jsonString, cls); } catch (Exception e) { // TODO: handle exception } return t; } /** * @param jsonString * json字符串 * @param cls * 要轉換的類 * @param <T> * 返回List * @return */ public static <T> List<T> getPersons(String jsonString, Class<T> cls) { List<T> list = new ArrayList<T>(); try { Gson gson = new Gson(); list = gson.fromJson(jsonString, new ListOfSomething<T>(cls)); } catch (Exception e) { e.printStackTrace(); } return list; } /** * @param jsonString * json字符串 * @return 返回 List<Map<String, Object>> */ public static List<Map<String, Object>> listKeyMaps(String jsonString) { List<Map<String, Object>> list = new ArrayList(); try { Gson gson = new Gson(); list = gson.fromJson(jsonString, new TypeToken<List<Map<String, Object>>>() { }.getType()); } catch (Exception e) { e.printStackTrace(); } return list; } }
public class ListOfSomething<T> implements ParameterizedType { private Class<?> wrapped; public ListOfSomething(Class<T> wrapped) { this.wrapped = wrapped; } public Type[] getActualTypeArguments() { return new Type[] { wrapped }; } public Type getRawType() { return List.class; } public Type getOwnerType() { return null; } }