gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:29:00 27 4
gpt4 key购买 nike

我是 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 循环,它可以循环数组上的数字,但无法做到这一点,但我只得到第一个玩家的名字,仅此而已,我什至无法到达第二个团队数组。我非常感谢您的帮助。

需要有关此代码的帮助

最佳答案

问题在于您的 POJO 模型类,它应该是 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)
}

关于Java如何获取JsonObject中包含JSONArray的特定值的集合(列表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61160865/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com