【问题标题】:How to get JSON object using Retrofit?如何使用 Retrofit 获取 JSON 对象?
【发布时间】:2022-01-21 23:03:39
【问题描述】:

我正在尝试使用 Retrofit 读取此 JSON,但出现此错误 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();

}

我不想将它们存储在任何模型中,我只想将 JSON 作为字符串获取

【问题讨论】:

    标签: android retrofit retrofit2


    【解决方案1】:

    你的界面应该是这样的:

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

    要获取原始 json 对象返回类型应该是Call&lt;ResponseBody&gt; 完成响应后,您可以像下面这样处理它:

    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 对象中设置字符串的方法。

    【讨论】:

    • 它正在工作,谢谢
    猜你喜欢
    • 1970-01-01
    • 2014-01-04
    • 1970-01-01
    • 2016-04-09
    • 2014-03-14
    • 1970-01-01
    • 2016-11-03
    • 2016-02-22
    • 1970-01-01
    相关资源
    最近更新 更多