Gson解析String为NULL转空字符串处理方案

创建以下两个类,手动对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,引用没有判断报空指针的问题

你可能感兴趣的:(Gson解析String为NULL转空字符串处理方案)