1.引入包
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
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);