Gson解析非String类型字段,数据为空字符串“”,导致解析报异常的解决方案

  • 写AdapterFactory类,实现TypeAdapterFactory接口
public class BaseJsonDataEmptyStringAdapterFactory implements TypeAdapterFactory {

    @Override
    public  TypeAdapter create(Gson gson, TypeToken typeToken) {

        Class rawType = typeToken.getRawType();
        TypeAdapter originAdapter = gson.getAdapter(typeToken);

        //如果是String类型,则直接用原来的Adapter转换
        return String.class.equals(rawType) ? originAdapter : new Adapter(gson,originAdapter, rawType);
    }

    private class Adapter extends TypeAdapter {

        private final Gson context;
        private final Class componentType;
        private final TypeAdapter componentTypeAdapter;

        public Adapter(Gson context, TypeAdapter componentTypeAdapter, Class componentType) {
            this.context = context;
            this.componentTypeAdapter =componentTypeAdapter;
            this.componentType = componentType;
        }

        @Override
        public void write(JsonWriter out, E value) throws IOException {
            if(componentTypeAdapter != null) {
                componentTypeAdapter.write(out, value);
            }
        }

        @Override
        public E read(final JsonReader in) throws IOException {

            //如果下一个为JsonToken.STRING的起点,说明是下个节点是字符串
            if (in.peek() == JsonToken.STRING) {
                in.skipValue();
                return null;
            }
            if(componentTypeAdapter != null) {
                return componentTypeAdapter.read(in);
            }
            return null;
        }
    }
}
  • 在有错误的字段加上@JsonAdapter即可
public class BaseJson implements Serializable{

    @JsonAdapter(BaseJsonDataEmptyStringAdapterFactory.class)
    private T data;
    private String code;
    private String error;
    private String message;
    ...
}

你可能感兴趣的:(Gson解析非String类型字段,数据为空字符串“”,导致解析报异常的解决方案)