簡體   English   中英

如何使用 Retrofit 獲得 JSON object?

[英]How to get JSON object using Retrofit?

I'm trying to read this JSON using Retrofit but I got this error Could not locate ResponseBody converter for class org.json.JSONObject.

ALE2 文件中的 JSON

{
   "a1":[...],
   "a2":[...],
   "a3":[...]
}

代碼

Retrofit retrofit = new Retrofit.Builder().baseUrl(Constants.BASE_URL).build();
retrofit.create(RetrofitInterface.class).getData().enqueue(new Callback < JSONObject > () {
    @Override
    public void onResponse(Call < JSONObject > call, Response < JSONObject > response) {

    }

    @Override
    public void onFailure(Call < JSONObject > call, Throwable t) {

    }
});

改造接口

public interface RetrofitInterface {

    @GET("ALE2")
    Call<JSONObject> getData();

}

我不想將它們存儲在任何 model 我只想將 JSON 作為字符串

您的界面應如下所示:

public interface RetrofitInterface {
    @GET("ALE2")
    Call<ResponseBody> getData();
}

要獲取原始 json object 返回類型應為Call<ResponseBody>完成響應后,您可以按如下方式處理它:

retrofit.create(RetrofitInterface.class).getData().enqueue(new Callback<ResponseBody> () {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            String responseBody = response.body().string();
            JSONObject json = new JSONObject(responseBody);
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {

        }
    });

這是在 JSON object 中設置字符串的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM