在第一次注冊并登陸的時候驯绎,服務端會返回用戶的信息。如果沒有默認值或返回的數(shù)據(jù)為null時昌跌,我們使用GsonConverterFactory
轉換器就會報空指針異常秉撇。以下方法針對返回的是String
的數(shù)據(jù)做一次轉換。
一個普通的Service創(chuàng)建
private static Retrofit userService = null;
public static UserService userApi() {
if (userService == null) {
Gson gson = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();
userService = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.client(mOkHttpClient)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return userService.create(UserService.class);
}
private static class NullStringToEmptyAdapterFactory<T> implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
Class<T> rawType = (Class<T>) type.getRawType();
if (rawType != String.class) {
return null;
}
return (TypeAdapter<T>) new StringNullAdapter();
}
}
private static class StringNullAdapter extends TypeAdapter<String> {
@Override
public String read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return "";
}
return reader.nextString();
}
@Override
public void write(JsonWriter writer, String value) throws IOException {
if (value == null) {
writer.nullValue();
return;
}
writer.value(value);
}
}
這樣就把model屬性值為null
的String
浑劳,轉換為""
阱持。