首页 > 解决方案 > 改造 API 调用(java)返回空对象

问题描述

这是我在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());
                }
            });

获取请求.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

标签: javaandroidretrofit2wear-os

解决方案


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

public class PlayerResponse {
    private GetRequest playerInfo;

    public GetRequest getPlayerInfo() {
        return playerInfo;
    }
}

并替换所有你JSONObjectPlayerResponse


推荐阅读