• 112737

    文章

  • 803

    评论

  • 12

    友链

  • 最近新加了换肤功能,大家多来逛逛吧~~~~
  • 喜欢这个网站的朋友可以加一下QQ群,我们一起交流技术。

Gson 解决Number类型处理问题

撸了今年阿里、腾讯和美团的面试,我有一个重要发现.......>>

Gson中默认类型是通过ObjectTypeAdapter来处理的

public final class ObjectTypeAdapter extends TypeAdapter<Object> {
  public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
    @SuppressWarnings("unchecked")
    @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
      if (type.getRawType() == Object.class) {
        return (TypeAdapter<T>) new ObjectTypeAdapter(gson);
      }
      return null;
    }
  };

  private final Gson gson;

  ObjectTypeAdapter(Gson gson) {
    this.gson = gson;
  }

  @Override public Object read(JsonReader in) throws IOException {
    JsonToken token = in.peek();
    switch (token) {
    case BEGIN_ARRAY:
      List<Object> list = new ArrayList<Object>();
      in.beginArray();
      while (in.hasNext()) {
        list.add(read(in));
      }
      in.endArray();
      return list;

    case BEGIN_OBJECT:
      Map<String, Object> map = new LinkedTreeMap<String, Object>();
      in.beginObject();
      while (in.hasNext()) {
        map.put(in.nextName(), read(in));
      }
      in.endObject();
      return map;

    case STRING:
      return in.nextString();

    case NUMBER:
      return in.nextDouble();

    case BOOLEAN:
      return in.nextBoolean();

    case NULL:
      in.nextNull();
      return null;

    default:
      throw new IllegalStateException();
    }
  }

  @SuppressWarnings("unchecked")
  @Override public void write(JsonWriter out, Object value) throws IOException {
    if (value == null) {
      out.nullValue();
      return;
    }

    TypeAdapter<Object> typeAdapter = (TypeAdapter<Object>) gson.getAdapter(value.getClass());
    if (typeAdapter instanceof ObjectTypeAdapter) {
      out.beginObject();
      out.endObject();
      return;
    }

    typeAdapter.write(out, value);
  }
}

但是对于number类型,自动处理成了double类型,导致model中的数值类型解析出错。

解决方案如下

public final class FreeDataModelTypeAdapter extends TypeAdapter<Object> {


  public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
    @SuppressWarnings("unchecked")
    @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
      if (type.getRawType() == Map.class || type.getRawType() == FreeDataModel.class) {
        return (TypeAdapter<T>) new FreeDataModelTypeAdapter();
      }
      return null;
    }
  };

  private final Gson gson;

  public FreeDataModelTypeAdapter() {
    this.gson = GsonUtils.createGson();
  }

  @Override public Object read(JsonReader in) throws IOException {
    JsonToken token = in.peek();
    switch (token) {
      case BEGIN_ARRAY:
        List<Object> list = new ArrayList<Object>();
        in.beginArray();
        while (in.hasNext()) {
          list.add(read(in));
        }
        in.endArray();
        return list;

      case BEGIN_OBJECT:
        Map<String, Object> map = new FreeDataModel();
        in.beginObject();
        while (in.hasNext()) {
          map.put(in.nextName(), read(in));
        }
        in.endObject();
        return map;

      case STRING:
        return in.nextString();

      case NUMBER:

        final String val = in.nextString();
        if(TextUtils.isDigitsOnly(val)) {
          return Long.parseLong(val);
        }else{
          return Double.parseDouble(val);
        }

      case BOOLEAN:
        return in.nextBoolean();

      case NULL:
        in.nextNull();
        return null;

      default:
        throw new IllegalStateException();
    }
  }

  @SuppressWarnings("unchecked")
  @Override public void write(JsonWriter out, Object value) throws IOException {
    if (value == null) {
      out.nullValue();
      return;
    }

    TypeAdapter<Object> typeAdapter = (TypeAdapter<Object>) gson.getAdapter(value.getClass());
    if (typeAdapter instanceof ObjectTypeAdapter) {
      out.beginObject();
      out.endObject();
      return;
    }

    typeAdapter.write(out, value);
  }
}

使用方式

        final GsonBuilder builder = new GsonBuilder();
        builder.serializeNulls();
        builder.registerTypeAdapter(Map.class,new FreeDataModelTypeAdapter()); //Map
        builder.registerTypeAdapter(FreeModal.class,new FreeDataModelTypeAdapter()); //自定义model
        builder.setVersion(VERSION);
        Gson gson = builder.create();

 

 


695856371Web网页设计师②群 | 喜欢本站的朋友可以收藏本站,或者加入我们大家一起来交流技术!

0条评论

Loading...


自定义皮肤 主体内容背景
打开支付宝扫码付款购买视频教程
遇到问题联系客服QQ:419400980
注册梁钟霖个人博客