Gson 源码解析

本文详细探讨了Gson库的源码解析过程,从Gson.fromJson()方法入手,分析了如何通过getAdapter()获取匹配的TypeAdapter,特别是聚焦于ReflectiveTypeAdapterFactory中的反射解析原理。文章还提到了JsonReader中的关键函数doPeek()及其调用链,并简单介绍了nextNonWhitespace()和fillBuffer()。最后,作者分享了自己实现的一个简单Json解析器的GitHub链接。
摘要由CSDN通过智能技术生成

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);
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值