Gson解析或者转换对象成json字符串时,String为NULL转空字符串处理方案

pzws@count / 文 发表于2016-05-25 15:19 次阅读 android

创建以下两个类,手动对String类型的字段进行处理

//NullStringToEmptyAdapterFactory.java

public class NullStringToEmptyAdapterFactory implements TypeAdapterFactory {
    public  TypeAdapter create(Gson gson, TypeToken type) {
        Class rawType = (Class) type.getRawType();        if (rawType != String.class) {
            return null;        }
        return (TypeAdapter) new StringNullAdapter();    }
}



//StringNullAdapter.java

public class StringNullAdapter extends TypeAdapter {
    @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.value("");            return;        }
        writer.value(value);    }
}
/**
*这里生成Gson时注册自定义处理String NULL值的TypeAdapter
*/
Gson gson = new GsonBuilder()
        .registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory())
        .setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
        .create();

这样就实现了解析null值String,引用没有判断报空指针的问题

收藏 赞 (0) 踩 (9)