android - 如何在 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
)
提前致谢。
解决方案
问题是您没有收到列表,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
)
这样,您将拥有一张玩家地图(对于此特定示例,您必须使用键ID8470607
和ID8473533
)
推荐阅读
- python - 按年份过滤行
- sql - 在两个表上使用联合
- javascript - Javascript - 将函数作为参数传递
- c# - VS Designer 现在显示 MainMenu
- swagger-ui - SwaggerUIBundle 和 SwaggerUi 有什么区别
- node.js - 使用 node.js http2 模块的服务器发送事件 - 我应该如何将它与流 / pushStream 一起使用?
- azure-service-fabric - 为 Service Fabric 本地群集启用 ResourceMonitorService 插件失败
- awk - 用 awk 替换大写或小写的字符串
- json - Ionic App 在 Android 设备上无法正常工作
- apache-kafka - 为什么这个 KStream/KTable 拓扑会传播未通过过滤器的记录?