Gson 解决Number类型处理问题

╄→гoц情女王★ 提交于 2020-08-10 09:40:02

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();

 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!