前言
之前也立過FLAG构捡,要閱讀gson的源碼嫉入,拖了好久抄淑,現(xiàn)在也算是填了之前的坑吧刻剥。
使用
- 轉(zhuǎn)換為json
Gson gson = new Gson();
User user = new User(18, "張三");
String userJson = gson.toJson(user);
- 轉(zhuǎn)換為對(duì)象
String json = "{\"age\":18,\"name\":\"張三\",\"sex\":\"女\"}";
User u = gson.fromJson(json, User.class);
User us = gson.fromJson(json, new TypeToken<User>() {
}.getType());
構(gòu)造方法
- 無(wú)參的
Gson gson = new Gson();
- Builder
Gson gson = new GsonBuilder().create();
常用的方法有
registerTypeAdapter
添加自己的解析器
registerTypeAdapterFactory
添加自己的解析器工廠
fromJson
fromJson
有多個(gè)重載方法,最后調(diào)用的是fromJson(JsonReader reader, Type typeOfT)
方法
public <T> T fromJson(JsonReader reader, Type typeOfT) throws JsonIOException, JsonSyntaxException {
boolean isEmpty = true;
boolean oldLenient = reader.isLenient();
reader.setLenient(true);
try {
reader.peek();
isEmpty = false;
TypeToken<T> typeToken = (TypeToken<T>) TypeToken.get(typeOfT);
TypeAdapter<T> typeAdapter = getAdapter(typeToken);
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) {
// TODO(inder): Figure out whether it is indeed right to rethrow this as JsonSyntaxException
throw new JsonSyntaxException(e);
} catch (AssertionError e) {
throw new AssertionError("AssertionError (GSON " + GsonBuildConfig.VERSION + "): " + e.getMessage(), e);
} finally {
reader.setLenient(oldLenient);
}
}
首先腻窒,我們來(lái)看JsonReader
它是個(gè)解析json
數(shù)據(jù)的輔助類昵宇,主要有以下方法
-
peek()
返回下一個(gè)元素的JsonToken
-
doPeek()
返回當(dāng)前元素的類型 -
hasNext()
是否有下個(gè)元素 -
beginArray()
數(shù)組開始 -
endArray()
數(shù)組結(jié)束 -
beginObject()
對(duì)象開始 -
endObject()
對(duì)象結(jié)束
然后是TypeAdapter<T> typeAdapter = getAdapter(typeToken);
public <T> TypeAdapter<T> getAdapter(TypeToken<T> type) {
TypeAdapter<?> cached = typeTokenCache.get(type == null ? NULL_KEY_SURROGATE : type);
if (cached != null) {
return (TypeAdapter<T>) cached;
}
Map<TypeToken<?>, FutureTypeAdapter<?>> threadCalls = calls.get();
boolean requiresThreadLocalCleanup = false;
if (threadCalls == null) {
threadCalls = new HashMap<TypeToken<?>, FutureTypeAdapter<?>>();
calls.set(threadCalls);
requiresThreadLocalCleanup = true;
}
// the key and value type parameters always agree
FutureTypeAdapter<T> ongoingCall = (FutureTypeAdapter<T>) threadCalls.get(type);
if (ongoingCall != null) {
return ongoingCall;
}
try {
FutureTypeAdapter<T> call = new FutureTypeAdapter<T>();
threadCalls.put(type, call);
for (TypeAdapterFactory factory : factories) {
TypeAdapter<T> candidate = factory.create(this, type);
if (candidate != null) {
call.setDelegate(candidate);
typeTokenCache.put(type, candidate);
return candidate;
}
}
throw new IllegalArgumentException("GSON (" + GsonBuildConfig.VERSION + ") cannot handle " + type);
} finally {
threadCalls.remove(type);
if (requiresThreadLocalCleanup) {
calls.remove();
}
}
}
首先,從緩存中取儿子,如果取不到瓦哎,則通過遍歷factories
對(duì)比Type
,拿到對(duì)應(yīng)的TypeAdapter
柔逼。
但是蒋譬,這個(gè)factories
是什么時(shí)候添加的呢?答案是構(gòu)造方法里
Gson(final Excluder excluder, final FieldNamingStrategy fieldNamingStrategy,
final Map<Type, InstanceCreator<?>> instanceCreators, boolean serializeNulls,
boolean complexMapKeySerialization, boolean generateNonExecutableGson, boolean htmlSafe,
boolean prettyPrinting, boolean lenient, boolean serializeSpecialFloatingPointValues,
LongSerializationPolicy longSerializationPolicy, String datePattern, int dateStyle,
int timeStyle, List<TypeAdapterFactory> builderFactories,
List<TypeAdapterFactory> builderHierarchyFactories,
List<TypeAdapterFactory> factoriesToBeAdded) {
...省略...
List<TypeAdapterFactory> factories = new ArrayList<TypeAdapterFactory>();
// built-in type adapters that cannot be overridden
factories.add(TypeAdapters.JSON_ELEMENT_FACTORY);
factories.add(ObjectTypeAdapter.FACTORY);
// the excluder must precede all adapters that handle user-defined types
factories.add(excluder);
// users' type adapters
factories.addAll(factoriesToBeAdded);
// type adapters for basic platform types
factories.add(TypeAdapters.STRING_FACTORY);
factories.add(TypeAdapters.INTEGER_FACTORY);
factories.add(TypeAdapters.BOOLEAN_FACTORY);
factories.add(TypeAdapters.BYTE_FACTORY);
factories.add(TypeAdapters.SHORT_FACTORY);
TypeAdapter<Number> longAdapter = longAdapter(longSerializationPolicy);
factories.add(TypeAdapters.newFactory(long.class, Long.class, longAdapter));
factories.add(TypeAdapters.newFactory(double.class, Double.class,
doubleAdapter(serializeSpecialFloatingPointValues)));
factories.add(TypeAdapters.newFactory(float.class, Float.class,
floatAdapter(serializeSpecialFloatingPointValues)));
factories.add(TypeAdapters.NUMBER_FACTORY);
factories.add(TypeAdapters.ATOMIC_INTEGER_FACTORY);
factories.add(TypeAdapters.ATOMIC_BOOLEAN_FACTORY);
factories.add(TypeAdapters.newFactory(AtomicLong.class, atomicLongAdapter(longAdapter)));
factories.add(TypeAdapters.newFactory(AtomicLongArray.class, atomicLongArrayAdapter(longAdapter)));
factories.add(TypeAdapters.ATOMIC_INTEGER_ARRAY_FACTORY);
factories.add(TypeAdapters.CHARACTER_FACTORY);
factories.add(TypeAdapters.STRING_BUILDER_FACTORY);
factories.add(TypeAdapters.STRING_BUFFER_FACTORY);
factories.add(TypeAdapters.newFactory(BigDecimal.class, TypeAdapters.BIG_DECIMAL));
factories.add(TypeAdapters.newFactory(BigInteger.class, TypeAdapters.BIG_INTEGER));
factories.add(TypeAdapters.URL_FACTORY);
factories.add(TypeAdapters.URI_FACTORY);
factories.add(TypeAdapters.UUID_FACTORY);
factories.add(TypeAdapters.CURRENCY_FACTORY);
factories.add(TypeAdapters.LOCALE_FACTORY);
factories.add(TypeAdapters.INET_ADDRESS_FACTORY);
factories.add(TypeAdapters.BIT_SET_FACTORY);
factories.add(DateTypeAdapter.FACTORY);
factories.add(TypeAdapters.CALENDAR_FACTORY);
factories.add(TimeTypeAdapter.FACTORY);
factories.add(SqlDateTypeAdapter.FACTORY);
factories.add(TypeAdapters.TIMESTAMP_FACTORY);
factories.add(ArrayTypeAdapter.FACTORY);
factories.add(TypeAdapters.CLASS_FACTORY);
// type adapters for composite and user-defined types
factories.add(new CollectionTypeAdapterFactory(constructorConstructor));
factories.add(new MapTypeAdapterFactory(constructorConstructor, complexMapKeySerialization));
this.jsonAdapterFactory = new JsonAdapterAnnotationTypeAdapterFactory(constructorConstructor);
factories.add(jsonAdapterFactory);
factories.add(TypeAdapters.ENUM_FACTORY);
factories.add(new ReflectiveTypeAdapterFactory(
constructorConstructor, fieldNamingStrategy, excluder, jsonAdapterFactory));
this.factories = Collections.unmodifiableList(factories);
}
可以看到愉适,基本上每個(gè)基本類型都有對(duì)應(yīng)的TypeAdapter
犯助,那么問題就來(lái)了,這里我們使用的是自定義的實(shí)體類维咸,是如何解析的剂买?
請(qǐng)注意最后添加的ReflectiveTypeAdapterFactory
,它就是解決自定義的實(shí)體類而存在的腰湾。
最后是T object = typeAdapter.read(reader);
根據(jù)上一步得到的TypeAdapter
雷恃,調(diào)用它的read
方法,這里我們就以ReflectiveTypeAdapterFactory#Adapter
的read
方法為例
@Override public T read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
// 反射創(chuàng)建實(shí)例
T instance = constructor.construct();
try {
in.beginObject();
while (in.hasNext()) {
// 獲取變量名
String name = in.nextName();
BoundField field = boundFields.get(name);
if (field == null || !field.deserialized) {
in.skipValue();
} else {
//調(diào)用 field.read設(shè)置值
field.read(in, instance);
}
}
} catch (IllegalStateException e) {
throw new JsonSyntaxException(e);
} catch (IllegalAccessException e) {
throw new AssertionError(e);
}
in.endObject();
return instance;
}
先用反射創(chuàng)建對(duì)象费坊,再循環(huán)取出每個(gè)值倒槐,然后調(diào)用field.read
為每個(gè)變量賦值。其中附井,boundFields
存放的是所有的變量名讨越,賦值是在getBoundFields
方法。
@Override public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {
Class<? super T> raw = type.getRawType();
if (!Object.class.isAssignableFrom(raw)) {
return null; // it's a primitive!
}
ObjectConstructor<T> constructor = constructorConstructor.get(type);
return new Adapter<T>(constructor, getBoundFields(gson, type, raw));
}
BoundField
的read
方法
@Override void read(JsonReader reader, Object value)
throws IOException, IllegalAccessException {
Object fieldValue = typeAdapter.read(reader);
if (fieldValue != null || !isPrimitive) {
field.set(value, fieldValue);
}
}
由此永毅,有以下結(jié)論
- 1.json中有該字段(對(duì)象)把跨、實(shí)體類中沒有 or 實(shí)體類中有、json中沒有沼死,都不影響解析
- 2.賦值是調(diào)用反射着逐,因此與實(shí)體類中是否有
get
、set
方法無(wú)關(guān)意蛀。
toJson
看完fromJson
耸别,再來(lái)看toJson
就會(huì)簡(jiǎn)單很多
toJson
也有很多重載方法,最后調(diào)用的是toJson(Object src, Type typeOfSrc, JsonWriter writer)
public void toJson(Object src, Type typeOfSrc, JsonWriter writer) throws JsonIOException {
TypeAdapter<?> adapter = getAdapter(TypeToken.get(typeOfSrc));
boolean oldLenient = writer.isLenient();
writer.setLenient(true);
boolean oldHtmlSafe = writer.isHtmlSafe();
writer.setHtmlSafe(htmlSafe);
boolean oldSerializeNulls = writer.getSerializeNulls();
writer.setSerializeNulls(serializeNulls);
try {
((TypeAdapter<Object>) adapter).write(writer, src);
} catch (IOException e) {
throw new JsonIOException(e);
} catch (AssertionError e) {
throw new AssertionError("AssertionError (GSON " + GsonBuildConfig.VERSION + "): " + e.getMessage(), e);
} finally {
writer.setLenient(oldLenient);
writer.setHtmlSafe(oldHtmlSafe);
writer.setSerializeNulls(oldSerializeNulls);
}
}
這里的邏輯和fromJson
類似县钥,根據(jù)傳入的Type
得到對(duì)應(yīng)的TypeAdapter
秀姐,然后調(diào)用它的write
方法,這里若贮,我們還是以ReflectiveTypeAdapterFactory#Adapter
為例
@Override public void write(JsonWriter out, T value) throws IOException {
if (value == null) {
out.nullValue();
return;
}
out.beginObject();
try {
for (BoundField boundField : boundFields.values()) {
if (boundField.writeField(value)) {
out.name(boundField.name);
boundField.write(out, value);
}
}
} catch (IllegalAccessException e) {
throw new AssertionError(e);
}
out.endObject();
}
首先是JsonWriter
省有,它也是輔助類痒留,主要有以下方法
-
beginArray()
寫入"[" -
endArray()
寫入"]" -
beginObject()
寫入"{" -
endObject()
寫入"}" -
beforeName()
寫入key前檢查 -
beforeValue()
寫入值前檢查 -
value(...)
寫入值
然后遍歷boundFields
,循環(huán)調(diào)用蠢沿。
BoundField
的write
方法
@Override void write(JsonWriter writer, Object value)
throws IOException, IllegalAccessException {
Object fieldValue = field.get(value);
TypeAdapter t = jsonAdapterPresent ? typeAdapter
: new TypeAdapterRuntimeTypeWrapper(context, typeAdapter, fieldType.getType());
t.write(writer, fieldValue);
}
BoundField
的writeField
方法
@Override public boolean writeField(Object value) throws IOException, IllegalAccessException {
if (!serialized) return false;
Object fieldValue = field.get(value);
return fieldValue != value; // 避免遞歸
}
總結(jié)
整個(gè)項(xiàng)目的架構(gòu)是建立在Adapter
模式上伸头,通過區(qū)分Type
從而拆分邏輯到各個(gè)Adapter
,其中也不乏Factory
模式舷蟀、緩存的使用熊锭,其對(duì)JsonReader
、JsonWriter
封裝也是值得學(xué)習(xí)的雪侥。