【问题标题】:Retrofit API call (java) returns empty object改造 API 调用(java)返回空对象
【发布时间】:2021-04-21 17:34:47
【问题描述】:

这是我在 java 中的第一个应用程序。我用 Ionic/Angular 制作了一个应用程序,我称之为api,一切正常。 现在我尝试对智能手表(Watch OS)做同样的事情,并且我使用 Retrofit 2.0 版本 2.4.0 和 GSON 2.4.0

implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'

我真的没有找到任何可以帮助我解决问题的教程/文档。

这是我的代码

MainActivity.java:

Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("https://new.scoresaber.com/")
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

            API api = retrofit.create(API.class);

            Call<JSONObject> call = api.getPosts();

            call.enqueue(new Callback<JSONObject>() {
                @Override
                public void onResponse(Call<JSONObject> call, Response<JSONObject> response) {
                    //When i debug then the response.body() is just empty
                    if (response.isSuccessful()) {
                        JSONObject res = response.body();
                        countryRank.setText(res.toString());
                    }
                    else{
                        countryRank.setText("Response was not successful");
                    }
                }

                @Override
                public void onFailure(Call<JSONObject> call, Throwable t) {
                    countryRank.setText("error: " + t.getMessage());
                }
            });

GetRequest.java

public class GetRequest {

@SerializedName("playerName")
private String playerName;
private String rank;
private String countryRank;
private String pp;


public String getPlayerName() {
    return playerName;
}

public String getRank() {
    return rank;
}

public String getCountryRank() {
    return countryRank;
}

public String getPp() {
    return pp;
}
}

API.java

import org.json.JSONObject;
import retrofit2.Call;
import retrofit2.http.GET;

public interface API {

    @GET("api/player/76561198280372610/basic")
    Call<JSONObject> getPosts();

}

感谢任何帮助!

n

【问题讨论】:

  • 当然我已经尝试过邮递员,那里一切正常!
  • 当你有 POJO 类为什么你使用 JSONObject
  • 就像我已经提到的,我是 Java 和改造的新手,我真的不知道我在做什么,你能告诉我我需要改变什么或做一些不同的事情

标签: java android retrofit2 wear-os


【解决方案1】:

只需为您的根对象再添加一个 POJO:

public class PlayerResponse {
    private GetRequest playerInfo;

    public GetRequest getPlayerInfo() {
        return playerInfo;
    }
}

并用PlayerResponse替换你所有的JSONObject

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 2017-01-16
    • 2018-01-22
    相关资源
    最近更新 更多