首页 > 解决方案 > 如何在 Kotlin 中使用 Retrofit 解析 JSON 中的无限对象列表

问题描述

我收到以下格式的 JSON 响应:

"game" : {},
"datetime": {},
"status": {},
"teams": {},
"players" : {
      "ID8470607" : {
        "id" : 8470607,
        "fullName" : "Brent Seabrook",
        "link" : "/api/v1/people/8470607",
        "firstName" : "Brent",
        "lastName" : "Seabrook",
        "primaryNumber" : "7",
        "birthDate" : "1985-04-20",
        "currentAge" : 34,
        "birthCity" : "Richmond",
        "birthStateProvince" : "BC",
        "birthCountry" : "CAN",
        "nationality" : "CAN",
        "height" : "6' 3\"",
        "weight" : 220,
        "active" : true,
        "alternateCaptain" : true,
        "captain" : false,
        "rookie" : false,
        "shootsCatches" : "R",
        "rosterStatus" : "Y",
        "currentTeam" : {
          "id" : 16,
          "name" : "Chicago Blackhawks",
          "link" : "/api/v1/teams/16",
          "triCode" : "CHI"
        },
        "primaryPosition" : {
          "code" : "D",
          "name" : "Defenseman",
          "type" : "Defenseman",
          "abbreviation" : "D"
        }
      },
      "ID8473533" : {
        "id" : 8473533,
        "fullName" : "Jordan Staal",
        "link" : "/api/v1/people/8473533",
        "firstName" : "Jordan",
        "lastName" : "Staal",
        "primaryNumber" : "11",
        "birthDate" : "1988-09-10",
        "currentAge" : 31,
        "birthCity" : "Thunder Bay",
        "birthStateProvince" : "ON",
        "birthCountry" : "CAN",
        "nationality" : "CAN",
        "height" : "6' 4\"",
        "weight" : 220,
        "active" : true,
        "alternateCaptain" : false,
        "captain" : true,
        "rookie" : false,
        "shootsCatches" : "L",
        "rosterStatus" : "Y",
        "currentTeam" : {
          "id" : 12,
          "name" : "Carolina Hurricanes",
          "link" : "/api/v1/teams/12",
          "triCode" : "CAR"
        },
        "primaryPosition" : {
          "code" : "C",
          "name" : "Center",
          "type" : "Forward",
          "abbreviation" : "C"
        }
      },

      etc.
},
"venue": {}

给定游戏的玩家名单是未知的(有些游戏是 40 人,有时是 42 人,它会发生变化)。如何将这些数据表示为 Kotlin 类?我尝试将其表示为 ArrayList,但解析时出现错误Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 111 column 18 path $.gameData.players

我知道这意味着它需要一个数组(我定义的那个),而是得到了 JSON 对象 ID8470607,但由于 ID 总是不同的,而且每次播放器列表的长度都会不同,我可以'不会像在其他类中那样在字段中进行硬编码。那么我应该如何将它表示为一个数据类呢?

这是我目前拥有的:

data class GameData (
    val game: GameInfo,
    val datetime: DateTime,
    val status: GameStatus,
    val teams: GameTeams,
    val players: ArrayList<Player>,
    val venue: GameVenue
)

提前致谢。

标签: androidjsonkotlinretrofit2

解决方案


问题是您没有收到列表,players因为示例中定义的是地图。如果您想解析上面显示的示例,您的 GameData 类需要如下所示:

data class GameData (
val game: GameInfo,
val datetime: DateTime,
val status: GameStatus,
val teams: GameTeams,
val players: Map<String,Player>,
val venue: GameVenue
)

这样,您将拥有一张玩家地图(对于此特定示例,您必须使用键ID8470607ID8473533


推荐阅读