我正在Retrofit使用Gson。如何自定义Gson将空响应(body为空)转换为空JSON对象{}
?
Gson gson = new GsonBuilder()
.setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'")
.serializeNulls()
.create();
new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setEndpoint(Api.API_URL)
.setClient(new OkClient(okHttpClient))
.setConverter(new GsonConverter(gson))
.setRequestInterceptor(new AddHeaderRequestInterceptor())
.build()
.create(Api.class);
更新
我的NullAdapter
未使用(here
和and here
未显示) - 我得到了
Gson gson = new GsonBuilder()
.registerTypeAdapter(Object.class, new NullAdapter())
.create();
System.out.println(gson.toJson(null).toString()); // produce null
class NullAdapter extends TypeAdapter<Object> {
@Override
public void write(JsonWriter out, Object value) throws IOException {
if(value == null) {
System.out.println("here");
out.beginObject().endObject().close();
return;
}
}
@Override
public Object read(JsonReader in) throws IOException {
System.out.println("and here");
return null;
}
}