package com.tian.mvc01.util;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
/**
* 描述:
* json转换工具类
*
* @author cui
* @create 2018-11-08 09:48
*/
public class JsonUtil {
/**
* java对象转字符串
*
* @param obj
* @return
*/
public static String javaBeanToJson(Object obj) {
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
return gson.toJson(obj);
}
/**
* json字符串转java对象
*
* @param json
* @param typeOfT
* @return
*/
public static Object jsonToJavaBean(String json, Type typeOfT) {
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
Object obj = gson.fromJson(json, typeOfT);
return obj;
}
/**
* 泛型约束List 转换字符串
*
* @param list
* @return
*/
public static String getGenericList(List<?> list) {
Type type = new TypeToken<List<?>>() {
}.getType();
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
.create();
return gson.toJson(list, type);
}
/**
* 字符串转换list对象
* @param json
* @return
*/
public static <T> List<T> jsonListToListBean(String json,Class<T> cls){
List<T> list = new ArrayList<T>();
try {
Gson gson = new Gson();
JsonArray arry = new JsonParser().parse(json).getAsJsonArray();
for (JsonElement jsonElement : arry) {
list.add(gson.fromJson(jsonElement, cls));
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}