gpt4 book ai didi

android - 来自 API 的数据在 for 循环中解析,结果不佳

转载 作者:行者123 更新时间:2023-11-30 05:08:58 26 4
gpt4 key购买 nike

我在 for 循环中解析来自 API ( https://statsapi.web.nhl.com/api/v1/standings) 的数据。在 Debug模式下,我看到来自 API 的数据是正确的,但是当我将第一条记录写入“tabulkaTimov”时,循环有 j=1(j=2,j=3,...等),我的第一条记录被下一个团队取代。

我的应用截图: https://ctrlv.cz/shots/2019/01/03/bbEf.png

这是NHL联赛的表。

public static List<TableTeamsModel> convertJsonToTableTeams(JsonObject data){
List<TableTeamsModel> tabulkaTimov = new ArrayList<>();
JsonArray pocetDivizii = data.get("records").getAsJsonArray();

for(int i=0;i<pocetDivizii.size();i++){

TableTeamsModel tabulka = new TableTeamsModel();

JsonObject division = pocetDivizii.get(i).getAsJsonObject();
tabulka.setDivisionName(division.get("division").getAsJsonObject().get("name").getAsString());

JsonArray teams = division.get("teamRecords").getAsJsonArray();

for(int j=0;j<teams.size();j++) {

JsonObject teamRecords = teams.get(j).getAsJsonObject();
tabulka.setTeamName(teamRecords.get("team").getAsJsonObject().get("name").getAsString());

tabulka.setGoalsGot(teamRecords.get("goalsAgainst").getAsInt());
tabulka.setGoalsScored(teamRecords.get("goalsScored").getAsInt());
tabulka.setPoints(teamRecords.get("points").getAsInt());
tabulka.setGamesPlayed(teamRecords.get("gamesPlayed").getAsInt());

tabulkaTimov.add(tabulka);
}
}
return tabulkaTimov;
}

最佳答案

看起来您正在 for 循环之外创建一个新的 tabulka 对象,然后将它多次添加到同一个数组列表中。这将添加一次(引用)并仅更新其内容。

这是你可以做的

public static List<TableTeamsModel> convertJsonToTableTeams(JsonObject data){
List<TableTeamsModel> tabulkaTimov = new ArrayList<>();
JsonArray pocetDivizii = data.get("records").getAsJsonArray();

for(int i=0;i<pocetDivizii.size();i++){

// Remove the creation of the tabulka object from here

JsonObject division = pocetDivizii.get(i).getAsJsonObject()
JsonArray teams = division.get("teamRecords").getAsJsonArray();

for(int j=0;j<teams.size();j++) {

JsonObject teamRecords = teams.get(j).getAsJsonObject();

// And then put the object creation here.
// as we did't have it above, the division name has to be set here too.

TableTeamsModel tabulka = new TableTeamsModel();
tabulka.setDivisionName(division.get("name").getAsString());
tabulka.setTeamName(teamRecords.get("team").getAsJsonObject().get("name").getAsString());
tabulka.setGoalsGot(teamRecords.get("goalsAgainst").getAsInt());
tabulka.setGoalsScored(teamRecords.get("goalsScored").getAsInt());
tabulka.setPoints(teamRecords.get("points").getAsInt());
tabulka.setGamesPlayed(teamRecords.get("gamesPlayed").getAsInt());

tabulkaTimov.add(tabulka);
}
}
return tabulkaTimov;
}

这样,您每次进入 ArrayList 时都会添加一个不同的/新的对象; - 而不是每次都添加对同一对象的相同引用并更新其数据。

关于android - 来自 API 的数据在 for 循环中解析,结果不佳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54024195/

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