- 写AdapterFactory类,实现TypeAdapterFactory接口
public class BaseJsonDataEmptyStringAdapterFactory implements TypeAdapterFactory {
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
Class<? super T> rawType = typeToken.getRawType();
TypeAdapter<T> originAdapter = gson.getAdapter(typeToken);
//如果是String类型,则直接用原来的Adapter转换
return String.class.equals(rawType) ? originAdapter : new Adapter(gson,originAdapter, rawType);
}
private class Adapter<E> extends TypeAdapter<E> {
private final Gson context;
private final Class<E> componentType;
private final TypeAdapter<E> componentTypeAdapter;
public Adapter(Gson context, TypeAdapter<E> componentTypeAdapter, Class<E> 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;
}
}
}
public class BaseJson<T> implements Serializable{
@JsonAdapter(BaseJsonDataEmptyStringAdapterFactory.class)
private T data;
private String code;
private String error;
private String message;
...
}