您需要注意,我们可以直接在SerializeNulls
实例上设置com.google.gson.stream.JsonWriter
功能。因此,让我们实现自定义com.google.gson.TypeAdapterFactory
,它将始终对Map
实例强制使用此功能:
class ForceNullsForMapTypeAdapterFactory implements TypeAdapterFactory {
public final <T> TypeAdapter<T> create(Gson gson,TypeToken<T> type) {
if (Map.class.isAssignableFrom(type.getRawType())) {
final TypeAdapter<T> delegate = gson.getDelegateAdapter(this,type);
return createCustomTypeAdapter(delegate);
}
return null;
}
private <T> TypeAdapter<T> createCustomTypeAdapter(TypeAdapter<T> delegate) {
return new TypeAdapter<T>() {
@Override
public void write(JsonWriter out,T value) throws IOException {
final boolean serializeNulls = out.getSerializeNulls();
try {
out.setSerializeNulls(true);
delegate.write(out,value);
} finally {
out.setSerializeNulls(serializeNulls);
}
}
@Override
public T read(JsonReader in) throws IOException {
return delegate.read(in);
}
};
}
}
简单用法:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
public class GsonApp {
public static void main(String[] args) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("nullKey",null);
map.put("other","Not Null!");
Foo foo = new Foo();
foo.setMyMap(map);
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapterFactory(new ForceNullsForMapTypeAdapterFactory())
.create();
System.out.println(gson.toJson(foo));
}
}
上面的代码显示:
{
"my_map": {
"nullKey": null,"other": "Not Null!"
}
}
本文链接:https://www.f2er.com/3131746.html