美文网首页
Gson解析工具类

Gson解析工具类

作者: 技术勤奋坚持 | 来源:发表于2018-08-22 18:38 被阅读0次
/**
 * 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 <T>
     * @return
     */
    public <T> T fromJson(String data, Class<T> 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解析工具类

      本文链接:https://www.haomeiwen.com/subject/cmnyiftx.html