io.github.stylesmile.tool.JsonGsonUtil Maven / Gradle / Ivy
package io.github.stylesmile.tool;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author Stylesmile
*/
public class JsonGsonUtil {
private static Gson gson = null;
static {
if (gson == null) {
gson = new Gson();
}
}
private JsonGsonUtil() {
}
/**
* to json
*
* @param object object
* @return String
*/
public static String objectToJson(Object object) {
String gsonString = null;
if (gson != null) {
gsonString = gson.toJson(object);
}
return gsonString;
}
/**
* 转成bean
*
* @param gsonString json string
* @param cls class
* @return t
*/
public static T jsonToObject(String gsonString, Class cls) {
T t = null;
if (gson != null) {
t = gson.fromJson(gsonString, cls);
}
return t;
}
/**
* 转成list
* 泛型在编译期类型被擦除导致报错
*
* @param gsonString gsonString
* @param cls class
* @return T
*/
public static List jsonToList(String gsonString, Class cls) {
List list = null;
if (gson != null) {
list = gson.fromJson(gsonString, new TypeToken>() {
}.getType());
}
return list;
}
/**
* 转成list中有map的
*
* @param gsonString json string
* @return t
*/
public static List