Gson 序列化String 默认值null - TFdream/blog GitHub Wiki

import java.io.IOException;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

public class StringNullAdapter extends TypeAdapter<String> {

	@Override  
    public void write(JsonWriter out, String value) throws IOException {  
        if (value == null) {  
            // out.nullValue();  
            out.value(""); // 序列化时将 null 转为 ""  
        } else {  
            out.value(value);  
        }  
    }  

    @Override  
    public String read(JsonReader in) throws IOException {  
        if (in.peek() == JsonToken.NULL) {  
            in.nextNull();  
            return null;  
        }  
        // return in.nextString();  
        String str = in.nextString();  
        if (str.equals("")) { // 反序列化时将 "" 转为 null  
            return null;  
        } else {  
            return str;  
        }  
    } 
}

构造Gson 实例:

Gson gson = new GsonBuilder().registerTypeAdapter(String.class, new StringNullAdapter()).create();
⚠️ **GitHub.com Fallback** ⚠️