簡體   English   中英

Java 如何獲取 JsonObject 中特定值的集合(列表)包含 JSONArray

[英]Java How to get collection(List) of specific values in JsonObject contains a JSONArray

我是 Java 的新手,我有一個 javabeans conatins

class Players{
@SerializedName("status")
@Expose
private String status;

@SerializedName("teamOne")
@Expose
private List<TeamOne> teamOne;

@SerializedName("teamTwo")
@Expose
private List<TeamTwo> teamTwo;

public String getStatus() {return status);}
public void setStatus(String status) {this.status = status;}

public List<TeamOne> getTeamOne(){ return teamOne:}
public setTeamOne(List<TeamOne> teamOne){ this.teamOne= teamOne:}

public List<TeamTwo> getTeamTwo(){ return teamTwo:}
public setTeamTwo(List<TeamTwo> teamTwo){ this.teamTwo= teamTwo;}

}

class TeamOne {
 @SerializedName("winningScore")
@Expose
private String winningScore;

@SerializedName("playerName")
@Expose
private String PlayerName;
}

class TeamTwo {
 @SerializedName("winningScore")
@Expose
private String winningScore;

@SerializedName("playerName")
@Expose
private String PlayerName;
}

我的 json 返回看起來像

{
"status":"BestPlayers",
"teamOne":[
   {
   "winningScore":"11",
   "playerName":"John"
   },
   {
   "winningScore":"11",
   "playerName":"David"
   }
],
"teamTwo":[
  {
   "winningScore":"15",
   "playerName":"Victor"
  },
 {
  "winningScore":"15",
  "playerName":"Thomas"
  }
]
}

現在我正在嘗試獲取兩支球隊的球員名單。 應該看起來 [John, David, Victor,Thomas]

我嘗試了一個 while 循環,它可以循環 arrays 上的任何數字,但無法做到這一點,但我只得到了第一個球員的名字,僅此而已,我什至無法到達第二個團隊陣列。 我將衷心感謝您的幫助。

需要有關此代碼的幫助

問題在於您的 POJO Model class 它應該是TeamDetailsTeam

    class Players{
    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("teamOne")
    @Expose
    private List<Team> teamOne;

    @SerializedName("teamTwo")
    @Expose
    private List<Team> teamTwo;
}


  class Team {
     @SerializedName("winningScore")
    @Expose
    private String winningScore;

    @SerializedName("playerName")
    @Expose
    private String PlayerName;
    }

現在創建一個玩家的最終名單,比如

private getTotalList(){
    List<Team> finalTeams=new ArrayList()
if(null!=teamOne && teamOne.size()>0){ // thats how your requirment will work
    finalTeams.add(teamOne)
}
//same goes for all teams add null check and add them.
 if(null!=teamTwo && teamTwo .size()>0){ // thats how your requirment will work
    finalTeams.add(teamTwo)
}



if(null!=funLovers && funLovers .size()>0){ 
        finalTeams.add(funLovers)
    }

        return finalTeams:
     }

然后使用 foreach 循環

for(Team  team: finalTeams){
Log.d("playerName: ", team.PlayerName)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM