Search code examples
javaandroidretrofit2wear-os

Retrofit API call (java) returns empty object


This is my first application in java. I made an app w ith Ionic/Angular where i am calling this api and everything works fine. Now im trying to do the same for smartwatches (Watch OS) and im using Retrofit 2.0 version 2.4.0 with GSON 2.4.0

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

I didnt really find any tutorials/documentations that helped me with my problem.

This is my code

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

}

Any help is appreciated!

n


Solution

  • Just add one more POJO for your root object:

    public class PlayerResponse {
        private GetRequest playerInfo;
    
        public GetRequest getPlayerInfo() {
            return playerInfo;
        }
    }
    

    And replace all your JSONObject's with PlayerResponse