Android-Gson学习

Gson

Gson 是 google 推出的工具库(JSON解析库)。不用写任何解析代码,Gson 就能自动把 JSON 数据映射到 Java 对象

官方文档

官方用户指南

使用 Gson

官方使用指南

  1. 导入依赖

    1
    2
    3
    dependencies {
    compile 'com.google.code.gson:gson:2.8.2'
    }
  2. Gson 基本用法

创建 Gson 对象

1
Gson gson=new Gson();

主要用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Serialization(序列化)
Gson gson = new Gson();
gson.toJson(1); // ==> 1
gson.toJson("abcd"); // ==> "abcd"
gson.toJson(new Long(10)); // ==> 10
int[] values = { 1 };
gson.toJson(values); // ==> [1]
// Deserialization(反序列化)
int one = gson.fromJson("1", int.class);
Integer one = gson.fromJson("1", Integer.class);
Long one = gson.fromJson("1", Long.class);
Boolean false = gson.fromJson("false", Boolean.class);
String str = gson.fromJson("\"abc\"", String.class);
String[] anotherStr = gson.fromJson("[\"abc\"]", String[].class);

toJson():用于将Java对象转换为相应的JSON数据

fromJson:用于将JSON数据转换为相应的Java对象

对象用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
// Serialization(序列化)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
// ==> json is {"value1":1,"value2":"abc"}
//Deserialization(反序列化)
BagOfPrimitives obj2=gson.fromJson(json,BagOfPrimitives.class);

数组用法

1
2
3
4
5
6
7
8
9
10
11
Gson gson = new Gson();
int[] ints = {1, 2, 3, 4, 5};
String[] strings = {"abc", "def", "ghi"};
// Serialization序列化
gson.toJson(ints); // ==> [1,2,3,4,5]
gson.toJson(strings); // ==> ["abc", "def", "ghi"]
// Deserialization反序列化
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);
// ==> ints2 will be same as ints json原先是数组对象,反序列化为java数组对象

集合用法

1
2
3
4
5
6
7
8
9
Gson gson = new Gson();//创建 Gson 对象
Collection<Integer> ints = Lists.immutableList(1,2,3,4,5); //创建一个int 的集合清单后面表示,创建一个不可变集合
// Serialization
String json = gson.toJson(ints); // ==> json is [1,2,3,4,5]
// Deserialization
Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();
Collection<Integer> ints2 = gson.fromJson(json, collectionType);
// ==> ints2 is same as ints

关于 immutable

关于 TypeToken


(*^▽^*)