封装Gson类静态调用

1.引入包

        
            com.google.code.gson
            gson
            2.8.5
        

2.封装类

public class GsonUtil {
    private static Gson gson = null;

    static {
        gson = new Gson();
    }

    /*对象转json串*/
    public static String toJson(Object o) {
        return gson.toJson(o);
    }

    /*从json串封装对象*/
    public static <T> T fromJson(String s, Class<T> cls) {
        return gson.fromJson(s, cls);
    }

}

3.调用


//toJson
A a = new A();
String json = GsonUtil.toJson(a);

//fromJson
A a = GsonUtil.fromJson(json, A.class);

你可能感兴趣的:(Java点滴,Gson)