Gson:将空体转换为空JSON对象{}

时间:2015-02-12 12:54:32

标签: gson retrofit

我正在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未使用(hereand 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;
        }
    }

0 个答案:

没有答案