/**
* JSON解析工具类
* Created by yao on 2018/8/22.
*/
public class GsonUtil {
private static GsonUtil instance = new GsonUtil();
private Gson gson;
public static GsonUtil getInstance() {
return instance;
}
private GsonUtil() {
gson = new Gson();
}
/**
* JSON转Bean
*
* @param data
* @param tClass
* @param <T>
* @return
*/
public <T> T fromJson(String data, Class<T> tClass) {
try {
if (gson == null) {
gson = new Gson();
}
return gson.fromJson(data, tClass);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Bean转JSON
* @param obj
* @return
*/
public String toJson(Object obj) {
try {
if (gson == null) {
gson = new Gson();
}
return gson.toJson(obj);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
网友评论