【源码阅读】Gson源码阅读

前言

之前也立过FLAG,要阅读gson的源码,拖了好久,现在也算是填了之前的坑吧。

使用

  • 转换为json
Gson gson = new Gson();
User user = new User(18, "张三");
String userJson = gson.toJson(user);
  • 转换为对象
String json = "{\"age\":18,\"name\":\"张三\",\"sex\":\"女\"}";
User u = gson.fromJson(json, User.class);
User us = gson.fromJson(json, new TypeToken() {
        }.getType());

构造方法

  • 无参的
    Gson gson = new Gson();
  • Builder
    Gson gson = new GsonBuilder().create();
    常用的方法有
    registerTypeAdapter 添加自己的解析器
    registerTypeAdapterFactory 添加自己的解析器工厂

fromJson

fromJson有多个重载方法,最后调用的是fromJson(JsonReader reader, Type typeOfT)方法

  public  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 typeToken = (TypeToken) TypeToken.get(typeOfT);
      TypeAdapter 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);
    }
  }

首先,我们来看JsonReader
它是个解析json数据的辅助类,主要有以下方法

  • peek() 返回下一个元素的JsonToken
  • doPeek() 返回当前元素的类型
  • hasNext() 是否有下个元素
  • beginArray() 数组开始
  • endArray() 数组结束
  • beginObject() 对象开始
  • endObject() 对象结束

然后是TypeAdapter typeAdapter = getAdapter(typeToken);

  public  TypeAdapter getAdapter(TypeToken type) {
    TypeAdapter cached = typeTokenCache.get(type == null ? NULL_KEY_SURROGATE : type);
    if (cached != null) {
      return (TypeAdapter) cached;
    }

    Map, FutureTypeAdapter> threadCalls = calls.get();
    boolean requiresThreadLocalCleanup = false;
    if (threadCalls == null) {
      threadCalls = new HashMap, FutureTypeAdapter>();
      calls.set(threadCalls);
      requiresThreadLocalCleanup = true;
    }

    // the key and value type parameters always agree
    FutureTypeAdapter ongoingCall = (FutureTypeAdapter) threadCalls.get(type);
    if (ongoingCall != null) {
      return ongoingCall;
    }

    try {
      FutureTypeAdapter call = new FutureTypeAdapter();
      threadCalls.put(type, call);

      for (TypeAdapterFactory factory : factories) {
        TypeAdapter 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对比Type,拿到对应的TypeAdapter
但是,这个factories是什么时候添加的呢?答案是构造方法里

  Gson(final Excluder excluder, final FieldNamingStrategy fieldNamingStrategy,
      final Map> instanceCreators, boolean serializeNulls,
      boolean complexMapKeySerialization, boolean generateNonExecutableGson, boolean htmlSafe,
      boolean prettyPrinting, boolean lenient, boolean serializeSpecialFloatingPointValues,
      LongSerializationPolicy longSerializationPolicy, String datePattern, int dateStyle,
      int timeStyle, List builderFactories,
      List builderHierarchyFactories,
      List factoriesToBeAdded) {
    ...省略...
    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);

    // 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 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);
  }

可以看到,基本上每个基本类型都有对应的TypeAdapter,那么问题就来了,这里我们使用的是自定义的实体类,是如何解析的?
请注意最后添加的ReflectiveTypeAdapterFactory,它就是解决自定义的实体类而存在的。

最后是T object = typeAdapter.read(reader);
根据上一步得到的TypeAdapter,调用它的read方法,这里我们就以ReflectiveTypeAdapterFactory#Adapterread方法为例

    @Override public T read(JsonReader in) throws IOException {
      if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
      }
      // 反射创建实例
      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 {
            //调用 field.read设置值
            field.read(in, instance);
          }
        }
      } catch (IllegalStateException e) {
        throw new JsonSyntaxException(e);
      } catch (IllegalAccessException e) {
        throw new AssertionError(e);
      }
      in.endObject();
      return instance;
    }

先用反射创建对象,再循环取出每个值,然后调用field.read为每个变量赋值。其中,boundFields存放的是所有的变量名,赋值是在getBoundFields方法。

  @Override public  TypeAdapter create(Gson gson, final TypeToken type) {
    Class raw = type.getRawType();

    if (!Object.class.isAssignableFrom(raw)) {
      return null; // it's a primitive!
    }

    ObjectConstructor constructor = constructorConstructor.get(type);
    return new Adapter(constructor, getBoundFields(gson, type, raw));
  }

BoundFieldread方法

     @Override void read(JsonReader reader, Object value)
          throws IOException, IllegalAccessException {
        Object fieldValue = typeAdapter.read(reader);
        if (fieldValue != null || !isPrimitive) {
          field.set(value, fieldValue);
        }
      }

由此,有以下结论

  • 1.json中有该字段(对象)、实体类中没有 or 实体类中有、json中没有,都不影响解析
  • 2.赋值是调用反射,因此与实体类中是否有getset方法无关。

toJson

看完fromJson,再来看toJson就会简单很多
toJson也有很多重载方法,最后调用的是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) 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类似,根据传入的Type得到对应的TypeAdapter,然后调用它的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,循环调用。
BoundFieldwrite方法

@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);
      }

BoundFieldwriteField方法

      @Override public boolean writeField(Object value) throws IOException, IllegalAccessException {
        if (!serialized) return false;
        Object fieldValue = field.get(value);
        return fieldValue != value; // 避免递归
      }

总结

整个项目的架构是建立在Adapter模式上,通过区分Type从而拆分逻辑到各个Adapter,其中也不乏Factory模式、缓存的使用,其对JsonReaderJsonWriter封装也是值得学习的。

你可能感兴趣的:(【源码阅读】Gson源码阅读)