Retrofit返回Json数据

在使用Retrofit的过程中,不需要Gson以及其他转换器,只是单纯的返回 JSONObject,那要怎么处理呢?
1.添加自定义Converter(注意选择相对应的版本)
2.把GsonConverterFactory.create(或者其他转换器)换成JsonConverterFactory.create()
具体代码如下:

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();
}

3.请求的接口

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

4.调用
异步:

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){

}
});

JsonConverterFactory github地址:https://github.com/brokge/Retrofit2.0-JSONCoverter

坚持原创技术分享,您的支持将鼓励我继续创作!