gpt4 book ai didi

ios - 获取嵌套 JSON 中的每个对象

转载 作者:行者123 更新时间:2023-11-28 10:14:25 27 4
gpt4 key购买 nike

所以在这里您可以看到我获取 JSON 的方法。我的问题是我希望我的循环遍历每个对象。没有一个物体像现在这样 10 倍。我知道 player["1"] 导致它重复获取第一个对象,这只是为了示例。我需要获取每个 player 信息。有人可以修正这个逻辑并稍微解释一下情况吗。

var homeTeamPlayers: [MatchUp]? = []

let urlRequest = URLRequest(url: URL(string: "http://www.fibalivestats.com/data/586746/data.json")!)

func fetchHomeTeam() {

let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in

if error != nil {
print(error!)
return
}

homeTeamPlayers = [MatchUp]()

do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]

if let teamsFromJSON = json["tm"] as? [String : AnyObject] {
if let homeTeam = teamsFromJSON["1"] as? [String : AnyObject] {
if let player = homeTeam["pl"] as? [String : AnyObject] {
for _ in player {
let homeTeamPlayer = MatchUp()
if let firstPlayer = player["1"] as? [String : AnyObject] {
if let name = firstPlayer["name"] as? String {

homeTeamPlayer.homeTeam_name = name

}
}

homeTeamPlayers?.append(homeTeamPlayer)
}
}
}
}
} catch let error {
print(error)
}
}

task.resume()
}

这是我想要获取的 JSON...

{

tm: {
1: {

pl: {
1: {

name: "R. Miniotas"

},
2: {

name: "T. Delininkaitis"

},
3: {

name: "V. Cizauskas"

},
4: {

name: "T. Klimavicius"

},
5: {

name: "V. Lipkevicius"

},
6: {

name: "M. LinkeviÄius"

},
7: {

name: "D. Seskus"

},
8: {

name: "T. Michnevicius"

},
9: {

name: "D. Gvezdauskas"

},
11: {

name: "A. Valeika"

}
}

最佳答案

您需要使用 for (key, value) in 语法枚举字典:

if let players = homeTeam["pl"] as? [String : Any] {
for (_, value) in players {
let homeTeamPlayer = MatchUp()
if let currentPlayer = value as? [String : Any],
let name = currentPlayer["name"] as? String {
homeTeamPlayer.homeTeam_name = name
}

homeTeamPlayers?.append(homeTeamPlayer)
}
}

但是为了避免空的 Matchup 实例,我建议

if let players = homeTeam["pl"] as? [String : Any] {
for (_, value) in players {
if let currentPlayer = value as? [String : Any],
let name = currentPlayer["name"] as? String {
let homeTeamPlayer = MatchUp()
homeTeamPlayer.homeTeam_name = name
homeTeamPlayers?.append(homeTeamPlayer)
}
}
}

注意:Swift 3 中的 JSON 字典是 [String:Any] 为什么 homeTeamPlayers 数组是可选的?

最后 - 一如既往 - .mutableContainers 在 Swift 中完全没有意义。

关于ios - 获取嵌套 JSON 中的每个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43212278/

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