1. 程式人生 > >Android Retrofit 2.0自定義Converter(JSONObject Converter)

Android Retrofit 2.0自定義Converter(JSONObject Converter)

如果在使用的過程中,不需要Gson以及其他轉換器,只是單純的返回 JSONObject,那這樣怎麼處理呢?

通過閱讀原始碼發現,可以通過自定義轉換器的方式操作:

import retrofit.Call
/*Retrofit 2.0*/

public interfase ApiService{
    @POST("/list")
    Call<JSONObject> loadRepo();
}

同步操作:

Call<JSONObject> call = service.loadRepo();
Repo repo = call.excute()

非同步操作:

Call<JSONObject> call = service.loadRepo();
call.enqueue(new Callback<JSONObject>(){
    @Override
    public void onResponse(Response<JSONObject> response){
        //從response.body()中獲取結果
    }
    @Override
    public void onFailure(Throwable t){

    }
});

這樣就完了麼?不。

  • 新增自定義Converter
  • GsonConverterFactory.create(gson)換成 JsonConverterFactory.create()

關鍵程式碼:

public class JsonConverterFactory extends Converter.Factory {

    public static JsonConverterFactory create() {
        return new JsonConverterFactory ();
    }

    @Override
    public Converter<ResponseBody, ?>
responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { return new JsonResponseBodyConverter<JSONObject>(); } @Override public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) { return new JsonRequestBodyConverter<JSONObject>(); } } final class JsonResponseBodyConverter<T> implements Converter<ResponseBody, T> { JsonResponseBodyConverter() { } @Override public T convert(ResponseBody value) throws IOException { JSONObject jsonObj; try { jsonObj = new JSONObject(value.string()); return (T) jsonObj; } catch(JSONException e) { return null; } } }

完整程式碼如下:

private static Retrofit initRetrofit() {
        OkHttpClient httpClient = new OkHttpClient();
        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient = new OkHttpClient.Builder().addInterceptor(logging).build();
        }
        return new Retrofit.Builder()
                .baseUrl(BaseUtil.getApiUrl())
                .addConverterFactory(JsonConverterFactory.create())
                .client(httpClient)
                .build();
    }