Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。可以使 JSON 字符串 和 Java 对象之间相互转换。
Gson目前托管在 github, https://github.com/google/gson
目前最新的版本为 2.6.2
Gson Download downloads at Maven Central
各种引用,按需使用。 比如,我在android studio中使用Gson
在项目的build.gradle中加入
compile 'com.google.code.gson:gson:2.6.2'
然后同步即可自动下载Gson库,即可在你的项目中使用Gson啦。
Gson API: Javadocs for the current Gson release
我们可以下载到本地,方便查看
Gson user guide: This guide contains examples on how to use Gson in your code.
等等…..
我们比较关心的就是这个API 了,入门最好的教程当然是官方提供的user guide了,下面我们就一步一步的来学习使用Gson。
https://github.com/google/gson/blob/master/UserGuide.md
// Serialization 序列化
Gson gson = new Gson() ;
System.out.println(gson.toJson(1));// 1
System.out.println(gson.toJson("abc")); // "abc"
System.out.println(gson.toJson(new Long(10))); // 10
int[] values = {1 ,2,3};
String array2Gson = gson.toJson(values);
System.out.println(array2Gson); // [1,2,3]
// Deserialization 发序列化
int one = gson.fromJson("1", int.class);
System.out.println(one); // 1
Integer one1 = gson.fromJson("1", Integer.class);
System.out.println(one1);// 1
Long one2 = gson.fromJson("1", Long.class);
System.out.println(one2);// 1
Boolean flag = gson.fromJson("false", Boolean.class);
System.out.println(flag); // false
String str = gson.fromJson("\"abc\"", String.class);
System.out.println(str);// abc
String[] arr =gson.fromJson("[\"abc\"]", String[].class);
System.out.println(arr); // [Ljava.lang.String;@704d4834
import com.google.gson.Gson;
public class ObjectExamples {
public static void main(String[] args) {
BagOfPrimitives bagOfPrimitives = new BagOfPrimitives();
Gson gson = new Gson();
String result = gson.toJson(bagOfPrimitives);
System.out.println(result); // {"value1":1,"value2":"abc","value3":["1","2","3","4"]}
}
static class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private String[] value3 = { "1", "2", "3", "4" };
//当对象被序列化时(写入字节序列到目标文件)时,transient阻止实例中那些用此关键字声明的变量持久化;
//当对象被反序列化时(从源文件读取字节序列进行重构),这样的实例变量值不会被持久化和恢复
private transient int value4 = 666; // 加了transient关键字不会被持久化,查看上面的输出结果
public BagOfPrimitives() {
super();
// no-args constructor
}
}
}
Note that you can not serialize objects with circular references since that will result in infinite recursion.
请注意,您不能序列化循环引用的对象,因为这将导致无限递归。
// Deserialization
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
// ==> obj2 is just like obj
注意事项: