java源码分析之gson

1:到官网看下 gson的主要作用就是 Java Objects 和 JSON 之间的相互转换. 我们看个最简单的例子.

 @AllArgsConstructor
public static class Book{
 private Integer id;
 private String name;
}

public static void main(String[] args) {
 Map map = Maps.newHashMap();
 map.put("1", new Book(1,"1"));
 map.put("2", new Book(2,"2"));
 map.put("3", new Book(3,"3"));
 final Gson gson = new Gson();
 final String json = gson.toJson(map);
 System.out.println(json);
 
 final Map map1 = gson.fromJson(json, new    TypeToken>(){}.getType());
 System.out.println(map1);
 
}
#输出结果
{"1":{"id":1,"name":"1"},"2":{"id":2,"name":"2"},"3":{"id":3,"name":"3"}}
{1=com.company.gson.Main$Book@491cc5c9, 2=com.company.gson.Main$Book@74ad1f1f, 3=com.company.gson.Main$Book@6a1aab78}

可见Java Object转成了json字符串,json字符串也反转为Java Object.
但此gson最值得研究的地方就是从json自符串到Java Object对象过程中, 他怎么知道要转换成Map这种对象结构? 即整个转换的理论到底是什么?

2:我们首先看下TypeToken到底是什么?

Map map1 =  gson.fromJson(json, new TypeToken>(){}.getType());

通过分析上面代码, new TypeToken>(){}.getType() 是实例化了一个匿名内部类对象, 并且调用了这个匿名内部类对象的getType()方法.
要想知道这个getType() 返回的是什么, 我们必须到TypeToken类中看下源码.

#类声明
public class TypeToken {
 final Class rawType;
 final Type type;
 final int hashCode;

#构造函数
@SuppressWarnings("unchecked")
protected TypeToken() {
 this.type = getSuperclassTypeParameter(getClass());
 this.rawType = (Class) $Gson$Types.getRawType(type);
 this.hashCode = type.hashCode();
}

public final Type getType() {
 return type;
}

可见TypeToken是个普通的泛型类. 而type变量就是保存了参数化类型对象. 见下图. 其实type就是ParameterizedType类型对象 实际实现类为sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.

通过该对象可以获取泛型的实际对象,
p.getActualTypeArguments();  
p.getRawType()

通过上面两个方法,就可以获取泛型的实际类型 即:
java.util.Map
实际就是我们匿名内部类传入的想要转成的Java Object.
java源码分析之gson_第1张图片
题外话: 想要弄清楚ParameterizedType 可以看下java里的Type接口的系列.
到此:我们可以得出结论,我们其实要反序列化,需要告诉gson反序列化后的类型是什么, 此处通过匿名内部类把泛型传入进去. gson通过ParameterizedType获取到实际的类型 [见ParameterizedType接口的方法].
3:继续分析源码

public  T fromJson(Reader json, Type typeOfT) throws JsonIOException, JsonSyntaxException {
 JsonReader jsonReader = newJsonReader(json);
 T object = (T) fromJson(jsonReader, typeOfT);
 assertFullConsumption(object, jsonReader);
 return object;
}

入参是json字符传 和 typeOfT[实际是参数化类型对象,可以获取泛型的实际类型]. 所以核心反序列化代码进入到

T object = (T) fromJson(jsonReader, typeOfT);

java源码分析之gson_第2张图片

只看核心代码

1:第一步
TypeToken typeToken = (TypeToken) TypeToken.get(typeOfT);
2:第二步
TypeAdapter typeAdapter = getAdapter(typeToken);
3:第三步
T object = typeAdapter.read(reader);

第一步:是通过TypeToken.get(typeOfT又返回一个TypeToken对象,此处可以进去看下是否还要我们的匿名内部类对象有关系.代码如下:

/**
 * Gets type literal for the given {@code Type} instance.
 */public static TypeToken get(Type type) {
 return new TypeToken(type);
} 
 

可见直接new了个TypeToken对象 并且把type直接传进去.

第二步:是通过typeToken对象返回一个TypeAdapter对象 直接看代码.
java源码分析之gson_第3张图片

可见核心代码是 List factories;
遍历factories 并调用每一个工厂方法,传入gson对象和type类型 生成对应的TypeAdapter.
至此:gson的核心思想也就找到了, 就是根据不同的type,生成不同的TypeAdapter.
当前的工厂对象有这么多
java源码分析之gson_第4张图片
找到factories初始化的地方.

List factories = new ArrayList();
// 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);
// user's type adapters
factories.addAll(typeAdapterFactories);
// 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 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);

可见gson给我们枚举了所有可能用到的工厂, 根据我们反序列化的类型,根据工厂对象生成对应的TypeAdapter,并进而完成反序列化.
第三步:就是通过TypeAdapter 把JSON转成Java Object对象

你可能感兴趣的:(json,gson,java,适配器,适配器模式)