我们可以使用自定义Gson转换器来解决此问题。以下是示例代码:
创建一个新的Gson转换器工厂:
public class NullStringToEmptyAdapterFactory implements TypeAdapterFactory {
@Override
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 StringAdapter();
private static class StringAdapter extends TypeAdapter<String> {
@Override
public void write(JsonWriter out, String value) throws IOException {
if (value == null || "null".equals(value)) {
out.nullValue();
} else {
out.value(value);
@Override
public String read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return "";
return in.nextString();
将此工厂添加到Retrofit实例中:
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory())
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
现在您的应用程序将在读取JSON响应时将null字符串值转换为空字符串。