json 帮助工具

import java.lang.reflect.Type;

import com.google.gson.Gson;

/**
 * json 帮助工具
 */
public final class GsonUtil {

    private GsonUtil() {

    }

    /**
     * Object转JSON对象
     *
     * @param obj
     * @return
     */
    public static String toJson(Object object) {
        String json = null;
        if (object != null) {
            Gson gson = new Gson();
            json = gson.toJson(object);
        }
        return json;
    }

    /**
     * 字符串转java对象
     *
     * @param str
     * @param clazz
     * @return
     */
    public static <T> T fromJson(String json, Class<T> clazz) {
        T t = null;
        if (json != null) {
            Gson gson = new Gson();
            t = gson.fromJson(json, clazz);
        }
        return t;
    }

    /**
     * 字符串转java对象
     * @param json
     * @param type
     * @return
     */
    public static <T> T fromJson(String json, Type type) {
        T t = null;
        if (json != null) {
            Gson gson = new Gson();
            t = gson.fromJson(json, type);
        }
        return t;
    }
}

原文地址:https://www.cnblogs.com/yanduanduan/p/5062497.html