改造 API 调用 (java) returns 空对象

Retrofit API call (java) returns empty object

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

的 Retrofit 2.0 版本 2.4.0
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'

我真的没有找到任何 tutorials/documentations 可以帮助我解决问题。

这是我的代码

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:

public class PlayerResponse {
    private GetRequest playerInfo;

    public GetRequest getPlayerInfo() {
        return playerInfo;
    }
}

并将所有 JSONObject 替换为 PlayerResponse