private Retrofit createRetrofit() {
return new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(buildGson()))
.client(okHttpClient())
.build();
}
private Gson buildGson() {
Gson gson = new GsonBuilder()
.registerTypeAdapter(Integer.class, new IntegerNullAdapter())
.registerTypeAdapter(int.class, new IntegerNullAdapter())
.create();
return gson;
}
public class IntegerNullAdapter extends TypeAdapter<Integer> {
@Override
public Integer read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return 0;
}
String stringValue = reader.nextString();
try{
return Integer.valueOf(stringValue);
}catch(NumberFormatException e){
return null;
}
}
@Override
public void write(JsonWriter writer, Integer value) throws IOException {
if (value == null) {
writer.nullValue();
return;
}
writer.value(value);
}
}
网友评论