gpt4 book ai didi

json - 嵌套 JSON Feed 返回错误

转载 作者:行者123 更新时间:2023-11-30 11:57:09 24 4
gpt4 key购买 nike

我对 JSON feed 和 swift 4 总体来说是新手。我在从嵌套 JSON 源打印数据时遇到问题。首先,我不确定在 do 语句中是否正确调用了数组。其次,当我构建应用程序时,我收到以下长错误。有人能帮我破译这个吗?我的代码位于帖子底部。先感谢您。

2017-12-06 12:58:48.604154-0500 PlayerRankDOTA2[91584:6694163] [BoringSSL] Function boringssl_context_get_peer_sct_list: line 1754 received sct extension length is less than sct data length Error jsonErr dataCorrupted(Swift.DecodingError.Context(codingPath: [PlayerRankDOTA2.PlayerStatsParent.(CodingKeys in _053A446F694D6B16CE13A0E302B3B14A).rankings, Foundation.(_JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue: "Index 0", intValue: Optional(0)), PlayerRankDOTA2.PlayerStats.(CodingKeys in _053A446F694D6B16CE13A0E302B3B14A).score], debugDescription: "Parsed JSON number <3099.96838722024> does not fit in Int.", underlyingError: nil))"

import UIKit

struct PlayerStatsParent:Decodable{
let rankings: [PlayerStats]
}

struct PlayerStats:Decodable {
let personaname: String
let score: Int
let solo_competitive_rank: Int
let avatar: String
}

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

let jsonUrlString = "https://api.opendota.com/api/rankings"
guard let url = URL(string: jsonUrlString) else {return}
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else {return}
//let dataAsString = String(data: data, encoding: .utf8)
//print(dataAsString)
do{
let playerStatsParent = try JSONDecoder().decode(PlayerStatsParent.self, from: data)
print(playerStatsParent.rankings)
} catch let jsonErr {
print("Error jsonErr", jsonErr)
}
}.resume()
}

let jsonUrlString = "https://api.opendota.com/api/rankings"

}

最佳答案

您必须对 PlayerStats 进行多项更改。首先,score 必须为 Double,因为这是 API 返回的格式。其次,JSON 响应中的所有值都可以为 null。解决此问题的一种方法是将所有属性定义为可选属性。

struct PlayerStats:Decodable {
let personaname: String?
let score: Double?
let solo_competitive_rank: Int?
let avatar: String?
}

PlayerStats 结构更改为上述格式后,解码工作正常。

关于json - 嵌套 JSON Feed 返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47680819/

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