cn.opencodes.utils.JsonUtils Maven / Gradle / Ivy
package cn.opencodes.utils;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import com.google.gson.Gson;
public class JsonUtils {
/**
* Object转成JSON数据
*/
public static String toJson(Object object){
if(object instanceof Integer || object instanceof Long || object instanceof Float ||
object instanceof Double || object instanceof Boolean || object instanceof String){
return String.valueOf(object);
}
return new Gson().toJson(object);
}
/**
* JSON数据,转成Object
*/
public static T fromJson(String json, Class clazz){
return new Gson().fromJson(json, clazz);
}
public static List fromJsonList(String json, Class clazz){
return new Gson().fromJson(json, new ParameterizedType() {
@Override
public Type getRawType() {
return List.class;
}
@Override
public Type[] getActualTypeArguments() {
return new Type[]{clazz};
}
@Override
public Type getOwnerType() {
return null;
}
});
}
}