Question

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":[]
      }
   }
}
Was it helpful?

Solution

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

OTHER TIPS

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.** {*; }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top