1、基本使用: 导入相关 pom
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.20</version> <optional>true</optional> </dependency>
<!-- gson --> <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency>
2、相关案例
package sun.rain.amazing.gson.quickstart; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonPrimitive; import com.google.gson.LongSerializationPolicy; import org.junit.Test; /** * @author sunRainAmazing */ public class GsonBaseTypeTest { private Gson gson = new Gson(); @Test public void testSerializer(){ // 这是两个不同的结果 System.out.println("a"); // a System.out.println("\"a\""); // "a" String i = gson.toJson(120); // 120 String lon = gson.toJson(120L); // 120 String ch = gson.toJson('A'); // "A" -- 带有双引号 String dou = gson.toJson(120.36); // 120.36 // Infinity is not a valid double value as per JSON specification. // String f = gson.toJson(Float.POSITIVE_INFINITY); // 报错 String f = gson.toJson(120.36); // 120.36 String bool = gson.toJson(false); //false String str = gson.toJson("tomcat"); // "tomcat" // 使用 扩展类型的 GsonBuilder gson = new GsonBuilder() // 把 long 类型 改成String类型 也可以自定义类型 .setLongSerializationPolicy(LongSerializationPolicy.STRING) // 设置特殊的 float 类型数据 如无限大 .serializeSpecialFloatingPointValues() .create(); i = gson.toJson(120); // 120 lon = gson.toJson(120L); // "120" -- 改变了输出策略 ch = gson.toJson('A'); // "A" dou = gson.toJson(120.36); //120.36 f = gson.toJson(Float.POSITIVE_INFINITY); // Infinity bool = gson.toJson(false); //false str = gson.toJson("tomcat"); //"tomcat" } // 进行反序列化 /** * 对于 单双引号 和 双 双引号 在反序列化 -- 是 一致的 */ @Test public void testDeserializer(){ int i = gson.fromJson("100", int.class); //100 double d = gson.fromJson("12.56", double.class); //12.56 double d1 = gson.fromJson("\"12.56\"", double.class); //12.56 String dr = gson.fromJson("12.56", String.class); //12.56 String dr1 = gson.fromJson("\"12.56\"", String.class); //12.56 boolean b = gson.fromJson("false", boolean.class); // false String str = gson.fromJson("tomcat", String.class); // tomcat } }