/**
* Gson转换工具类
*/
public class GsonUtils {
/**
* @param jsonString
* json字符串
* @param cls
* 要转换的类
* @param
* 返回要转换的类
* @return
*/
public static T getPerson(String jsonString, Class 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
* 返回List
* @return
*/
public static List getPersons(String jsonString, Class cls) {
List list = new ArrayList();
try {
Gson gson = new Gson();
list = gson.fromJson(jsonString, new ListOfSomething(cls));
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* @param jsonString
* json字符串
* @return 返回 List>
*/
public static List> listKeyMaps(String jsonString) {
List> list = new ArrayList();
try {
Gson gson = new Gson();
list = gson.fromJson(jsonString, new TypeToken>>() {
}.getType());
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
public class ListOfSomething implements ParameterizedType {
private Class> wrapped;
public ListOfSomething(Class wrapped) {
this.wrapped = wrapped;
}
public Type[] getActualTypeArguments() {
return new Type[] { wrapped };
}
public Type getRawType() {
return List.class;
}
public Type getOwnerType() {
return null;
}
}