Gson解析工具类

/**
 * 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 
     * @return
     */
    public  T fromJson(String data, Class 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;
        }
    }
}

你可能感兴趣的:(Gson解析工具类)