簡體   English   中英

如何使用 Java 中的 Retrofit 解析嵌套的多個 Json 對象

[英]How to Parse Nested - Multiple Json Objects using Retrofit in Java

我遇到了 Retrofit 的問題。

當我打電話給我的 REST API 時,每次response.body()都不成功並且 null

我嘗試使用 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()不成功和 null

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

成功 Postman 響應:

在此處輸入圖像描述

您可以在 postman 本身中生成等效的 java 請求代碼

在此處輸入圖像描述

暫無
暫無

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

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