Retrofit返回具有null成员的对象

时间:2014-04-11 01:04:12

标签: android gson retrofit

当我尝试使用Retrofit解析以下JSON时,我最终得到了null成员对象。

解析:

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

游戏类:

@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;
}

团队课程:

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

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

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

示例JSON:

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

2 个答案:

答案 0 :(得分:8)

JSON包含顶级"游戏"条目,因此您无法直接反序列化游戏实例。您需要另一种类型具有Game类型的字段来表示响应。

public class Response {
    public final Game game;

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

您可以将JSON放在一个字符串中,并直接使用Gson来测试如何反序列化响应。这种行为几乎与Retrofit无关,而与Gson的行为有关。

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

答案 1 :(得分:1)

还有一个原因可能有些类似的行为:在这种情况下,调试器实际上没有从Retrofit返回的响应的字段成员。

其原因是proguard。如果您使用的是minifyEnabled true,请确保明确告诉它保留您的POJO。它可以是这样的:

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