本文记录的是如何使用Gson序列化和反序列化包含不同类型对象的 JSON Array,例如:

1
['hello',5,{name:'GREETINGS',source:'guest'}]

对于这种情况看,使用 Gson toJson(collection) 序列化,无需做额外的工作都能够得到正确的结果,但是,使用 fromJson(json, Collection.class) 反序列化时不能得到期望结果,因为Gson不知道如何将集合中元素与其类型对应起来。可采用如下解决方法: 使用Gson parser API(JsonParser)解析数组中每个元素,然后对数组中每个元素使用Gson.fromJson()进行反序列化。示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.util.ArrayList;
import java.util.Collection;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;

public class GsonCollection {
static class Event {
private String name;
private String source;

private Event(String name, String source) {
this.name = name;
this.source = source;
}

@Override
public String toString() {
return String.format("(name=%s, source=%s)", name, source);
}
}

@SuppressWarnings({ "unchecked", "rawtypes" })
public static void main(String[] args) {
Gson gson = new Gson();
Collection collection = new ArrayList();
collection.add("hello");
collection.add(5);
collection.add(new Event("GREETINGS", "guest"));
String json = gson.toJson(collection);
System.out.println("Using Gson.toJson() on a raw collection: " + json);
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(json).getAsJsonArray();
String message = gson.fromJson(array.get(0), String.class);
int number = gson.fromJson(array.get(1), int.class);
Event event = gson.fromJson(array.get(2), Event.class);
System.out.printf("Using Gson.fromJson() to get: %s, %d, %s", message,
number, event);
}
}

控制台输出为:

1
2
Using Gson.toJson() on a raw collection: ["hello",5,{"name":"GREETINGS","source":"guest"}]
Using Gson.fromJson() to get: hello, 5, (name=GREETINGS, source=guest)

译自:

Gson User Guide