Gson使用方法:
Gson.fromJson(String json, Class clazz)
所以从 fromJson 开始解析
Gson.java
fromJson() 有多个重载函数,最终都会调用下面这个
public <T> T fromJson(JsonReader reader, Type typeOfT) throws JsonIOException, JsonSyntaxException {
boolean isEmpty = true;
boolean oldLenient = reader.isLenient(); // lenient : 宽容
reader.setLenient(true);
try {
reader.peek(); // 返回下一个标记 但不会消耗, 应该是为了看看是否抛出异常
isEmpty = false;
// TypeToken 就是对 Type 的一个封装
TypeToken<T> typeToken = (TypeToken<T>) TypeToken.get(typeOfT); // 根据Type获取对应的 TypeToken
TypeAdapter<T> typeAdapter = getAdapter(typeToken); // 获取对应的 adapter
T object = typeAdapter.read(reader);
return object;
} catch (EOFException e) {
/*
* For compatibility with JSON 1.5 and earlier, we return null for empty
* documents instead of throwing.
*/
if (isEmpty) {
return null;
}
throw new JsonSyntaxException(e);
} catch (IllegalStateException e) {
throw new JsonSyntaxException(e);
} catch (IOException e) {
throw new JsonSyntaxException(e);
} finally {
reader.setLenient(oldLenient);
}
}
public <T> TypeAdapter<T> getAdapter(TypeToken<T> type) {
// 省略部分代码
try {
FutureTypeAdapter<T> call = new FutureTypeAdapter<T>();
threadCalls.put(type, call);
// 遍历所有的 TypeAdapterFactory ,找到匹配的 Adapter
// TypeAdapterFactory.create() 会返回对应的 TypeAdapter, 如果 TypeToken 不符合的话返回 null
for (TypeAdapterFactory factory : factories) {
TypeAdapter<T> candidate = factory.create(this, type);
if (candidate != null) {
call.setDelegate(candidate);
typeTokenCache.put(type, candidate);