문제

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":[]
      }
   }
}
도움이 되었습니까?

해결책

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

다른 팁

다소 비슷한 동작을위한 더 많은 이유가있을 수 있습니다.이 경우 디버거는 실제로 Retrofit에서 반환 된 응답을위한 필드 구성원이 없습니다.


그리고 그 이유는 proguard입니다.minifyEnabled true를 사용하는 경우 Pojos를 유지하도록 명시 적으로 알려주십시오.그것은 그런 뭔가 일 수 있습니다 :

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top