swift 解析JSON错误“应解码数组< Any>,但找到的却是数字

1rhkuytd  于 2023-02-18  发布在  Swift
关注(0)|答案(1)|浏览(172)

我试图显示来自虚假后端JSON文件的数据。我试图从“shipment_items”键侧的数组中收集数据。我知道代码结构不正确,因为我一直收到错误
类型不匹配(Swift.数组,Swift.解码错误.上下文(编码路径:[_JSON密钥(字符串值:“id”,整数值:nil)],调试说明:“应解码数组,但找到的是数字。",underlyingError:无))

struct Items: Codable {
    var itemName: String?
    var price: Int?
    var brand: String?
    var size: String?

}
//Custom Keys
enum CodingKeys: String, CodingKey{
    case itemName = "name"
    case price = "price"
    case brand = "brand"
    case size = "size"
}

func parseData(){
    guard let url = URL(string: "https://xxxxxxx")
        else {return}
    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard let dataResponse = data,
            error == nil else {
                print(error?.localizedDescription ?? "Error")
                return }
        do{
            let decoder = JSONDecoder()

            let model = try decoder.decode([String:[Items]].self, from: dataResponse)
            print(model["shipment_items"])

        } catch let parsingError {
            print("Error", parsingError)
        }
    }
    task.resume()
}
von4xj4u

von4xj4u1#

错误很明显:请查看JSON的根对象,关键字id的值为5,这是Int,而不是[Items]。这是 * 预期解码Array,但找到了一个数字 * 所告诉您的。
必须为根对象添加一个伞状结构。
price的类型是String,双引号中的所有内容都是String

struct Root : Decodable {
    let id : Int
    let items : [Item]

    enum CodingKeys: String, CodingKey { case id, items = "shipment_items" }
}

struct Item : Decodable {
    let itemName: String
    let price: String
    let brand: String
    let size: String

    enum CodingKeys: String, CodingKey {
        case itemName = "name", price, brand, size
    }
}

并解码

let model = try decoder.decode(Root.self, from: dataResponse)
print(model.items)

相关问题