【问题标题】:How to Parse Nested - Multiple Json Objects using Retrofit in Java如何在 Java 中使用 Retrofit 解析嵌套的多个 Json 对象
【发布时间】:2021-05-19 04:17:17
【问题描述】:

我遇到了改造问题。

当我调用我的 REST API 时,每次 response.body() 不成功并且为空

我尝试与 Postman 进行相同的呼叫,但正文包含正确答案。

JSON 响应正文:

{
    "error": false,
    "message": "API-Request successful",
    "users": {
        "0": {
            "userID": 11,
            "firstName": "David",
            "userName": "david",
            "birthDate": "2020-10-19",
            "gender": 1,
            "country": "Linz",
            "aboutmeText": "Testeintrag 3",
            "status": "I like Lookly."
        },
        "1": {
            "userID": 43,
            "firstName": "Sarah",
            "userName": "sarahh",
            "birthDate": "2001-12-14",
            "gender": 0,
            "country": "Austria",
            "aboutmeText": "Lookly ist eine hervorragende App!",
            "status": "Hey there! I am using Lookly."
        }
    }
}

我的请求: response.body() 不成功且为空

public void updateListView(String latitude, String longitude) {
        Call<ResponseBody> call = RetrofitClient
                .getInstance()
                .getApi()
                .standard(
                        latitude,
                        longitude
                );

        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if(response.isSuccessful()) {
                    //the response-body is already parseable to your ResponseBody object
                    ResponseBody responseBody = (ResponseBody) response.body();
                    //you can do whatever with the response body now...
                    String responseBodyString= null;
                    try {
                        responseBodyString = responseBody.string();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    Log.d("Response body", responseBodyString);
                }
                else  {
                    Log.d("Response errorBody", String.valueOf(response.errorBody()));
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.e("onFalure", t.getMessage());
                Toast.makeText(TestRequest.this, t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }

邮递员响应成功:

【问题讨论】:

  • 您能发布到目前为止您尝试过的内容吗?
  • 如果 response.successful 为 false 那么你的 api 实现是错误的
  • 但是,在邮递员中我得到了成功的响应?
  • 你也可以从邮递员那里得到那个api的okHttp请求代码

标签: java android json postman retrofit


【解决方案1】:

您可以在邮递员本身中生成等效的请求 java 代码

【讨论】:

    猜你喜欢
    • 2015-09-12
    • 2021-02-03
    • 2016-01-01
    • 2018-05-31
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 2019-07-30
    相关资源
    最近更新 更多