【源碼閱讀】Gson源碼閱讀

前言

之前也立過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#Adapterread方法為例

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

BoundFieldread方法

     @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í)體類中是否有getset方法無(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)用蠢沿。
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; // 避免遞歸
      }

總結(jié)

整個(gè)項(xiàng)目的架構(gòu)是建立在Adapter模式上伸头,通過區(qū)分Type從而拆分邏輯到各個(gè)Adapter,其中也不乏Factory模式舷蟀、緩存的使用熊锭,其對(duì)JsonReaderJsonWriter封裝也是值得學(xué)習(xí)的雪侥。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市精绎,隨后出現(xiàn)的幾起案子速缨,更是在濱河造成了極大的恐慌,老刑警劉巖代乃,帶你破解...
    沈念sama閱讀 206,311評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件旬牲,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡搁吓,警方通過查閱死者的電腦和手機(jī)原茅,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,339評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)堕仔,“玉大人擂橘,你說我怎么就攤上這事∧牵” “怎么了通贞?”我有些...
    開封第一講書人閱讀 152,671評(píng)論 0 342
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)恼五。 經(jīng)常有香客問我昌罩,道長(zhǎng),這世上最難降的妖魔是什么灾馒? 我笑而不...
    開封第一講書人閱讀 55,252評(píng)論 1 279
  • 正文 為了忘掉前任茎用,我火速辦了婚禮,結(jié)果婚禮上睬罗,老公的妹妹穿的比我還像新娘轨功。我一直安慰自己,他們只是感情好傅物,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,253評(píng)論 5 371
  • 文/花漫 我一把揭開白布夯辖。 她就那樣靜靜地躺著,像睡著了一般董饰。 火紅的嫁衣襯著肌膚如雪蒿褂。 梳的紋絲不亂的頭發(fā)上圆米,一...
    開封第一講書人閱讀 49,031評(píng)論 1 285
  • 那天,我揣著相機(jī)與錄音啄栓,去河邊找鬼娄帖。 笑死,一個(gè)胖子當(dāng)著我的面吹牛昙楚,可吹牛的內(nèi)容都是我干的近速。 我是一名探鬼主播,決...
    沈念sama閱讀 38,340評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼堪旧,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼削葱!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起淳梦,我...
    開封第一講書人閱讀 36,973評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤析砸,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后爆袍,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體首繁,經(jīng)...
    沈念sama閱讀 43,466評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,937評(píng)論 2 323
  • 正文 我和宋清朗相戀三年陨囊,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了弦疮。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,039評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡蜘醋,死狀恐怖胁塞,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情堂湖,我是刑警寧澤闲先,帶...
    沈念sama閱讀 33,701評(píng)論 4 323
  • 正文 年R本政府宣布,位于F島的核電站无蜂,受9級(jí)特大地震影響伺糠,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜斥季,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,254評(píng)論 3 307
  • 文/蒙蒙 一训桶、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧酣倾,春花似錦舵揭、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,259評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至映之,卻和暖如春拦焚,著一層夾襖步出監(jiān)牢的瞬間蜡坊,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,485評(píng)論 1 262
  • 我被黑心中介騙來(lái)泰國(guó)打工赎败, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留秕衙,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,497評(píng)論 2 354
  • 正文 我出身青樓僵刮,卻偏偏與公主長(zhǎng)得像据忘,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子搞糕,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,786評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容