Swift Dictionary API "No value associated with key CodingKeys(stringValue: \"type\", intValue: nil) (\"type\").", underlyingError: nil))

Swift Dictionary API "No value associated with key CodingKeys(stringValue: \"type\", intValue: nil) (\"type\").", underlyingError: nil))

我 运行 遇到一个错误,显示我试图从 API 中获取的“类型”没有值。我尝试查看围绕此展开的其他帖子,但找不到任何对我有用的东西而不导致出现不同的问题。

我得到的完整错误是“No value associated with key CodingKeys(stringValue: "type", intValue: nil) ("type").", underlyingError: nil))

我要从中获取的 API 是:https://github.com/ToontownRewritten/api-doc/blob/master/invasions.md

import UIKit

struct InvasionList: Decodable {
    let type: String
    let asOf: Int?
    let progress: String?
    
    
}

class ViewController: UIViewController {
    

    override func viewDidLoad() {
        super.viewDidLoad()
        let jsonUrlString = "https://www.toontownrewritten.com/api/invasions"
        guard let url = URL(string: jsonUrlString) else { return }
        
        URLSession.shared.dataTask(with: url) { (data, response, err) in
            
            guard let data = data else {return }
            
            do {
                let invasions = try JSONDecoder().decode(InvasionList.self, from: data)
                print(invasions.type)
            
            
            } catch let err {
                print(err)
            }
            
            
            }.resume()
        
    }


}

您的 InvasionList 实际上与您尝试解码的 JSON 的结构不匹配。它匹配它的一小部分,但你需要解码整个东西。这包括最外层的包装器(带有 lastUpdated 的部分和每个“入侵”的动态键)。

这是一个工作示例:

let jsonData = """
   {"lastUpdated":1624230138,"invasions":{"Gulp Gulch":{"asOf":1624230127,"type":"Robber Baron","progress":"3797/7340"},"Splashport":{"asOf":1624230129,"type":"Ambulance Chaser","progress":"2551/8000"},"Kaboom Cliffs":{"asOf":1624230131,"type":"Money Bags","progress":"5504/6000"},"Boingbury":{"asOf":1624230132,"type":"Tightwad","progress":"4741/8580"}},"error":null}
""".data(using: .utf8)!

struct InvasionWrapper: Decodable {
    let lastUpdated : Int
    let invasions : [String:Invasion]
}

struct Invasion: Decodable {
    let type: String
    let asOf: Int?
    let progress: String?
}

do {
    let list = try JSONDecoder().decode(InvasionWrapper.self, from: jsonData)
    print(list)
} catch {
    print(error)
}