OrhanC1
OrhanC1

Reputation: 1410

Retrofit returns object with null members

When I try to parse the following JSON with Retrofit, I end up with null member objects.

Parsing:

RestAdapter restAdapter = new RestAdapter.Builder()
        .setEndpoint(CallerInfo.API_URL)
        .setLogLevel(RestAdapter.LogLevel.FULL)
        .build();
InGameInfo igi = restAdapter.create(InGameInfo.class);
Game game = igi.fetchInGameInfo("EUW", "sasquatching");
Log.d("Cancantest", "Game " + game); //Not null
Log.d("Cancantest", "Team one " + game.getTeamOne()); //Null

Game Class:

@SerializedName("teamTwo")
@Expose private Team teamTwo;
@SerializedName("teamOne")
@Expose private Team teamOne;

public void setTeamOne(Team teamOne) {
    this.teamOne = teamOne;
}

public void setTeamTwo(Team teamTwo) {
    this.teamTwo = teamTwo;
}

public Team getTeamOne() {
    return teamOne;
}

public Team getTeamTwo() {
    return teamTwo;
}

Team Class:

@SerializedName("array")
@Expose private TeamMember[] teamMembers;

public void setTeamMembers(TeamMember[] teamMembers) {
    this.teamMembers = teamMembers;
}

public TeamMember[] getTeamMembers() {
    return teamMembers;
}

Example JSON:

{
   "game":{
      "teamTwo":{
         "array":[]
      },
      "teamOne":{
         "array":[]
      }
   }
}

Upvotes: 2

Views: 4394

Answers (2)

Nikita Barishok
Nikita Barishok

Reputation: 1322

There can be one more reason for somewhat similar behavior: in this case debugger actually has no field members for the response returned from Retrofit.

And the reason for that is proguard. If you are using minifyEnabled true, make sure you explicitly tell it to keep your POJOs. It can be something like that:

#save model classes
-keep class com.example.app.**.model.** {*; }

Upvotes: 2

Jake Wharton
Jake Wharton

Reputation: 76075

The JSON contains a top level "game" entry so you cannot directly deserialize an instance of game. You need another type which has a field of type Game that represents the response.

public class Response {
    public final Game game;

    public Response(Game game) {
        this.game = game;
    }
}

You can put your JSON in a string and use Gson directly to test how the response will be deserialized. This behavior has almost nothing to do with Retrofit and all to do with the behavior of Gson.

String data = "...";
Game game = gson.fromJson(data, Game.class);
Response response = gson.fromJson(data, Response.class);

Upvotes: 7

Related Questions