1

目前正在尝试将 json 字典快速解析到屏幕上,但是我遇到了这个序列协议错误,还有一个类型不匹配错误,它获取一个字符串/数据并期望一个 Int. 错误是“类型'ProductResponse'不符合协议'Sequence'”和

"typeMismatch(Swift.Int, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "code", intValue: nil)], debugDescription: "预期解码 Int 但找到了一个字符串/数据。",底层错误: nil ))”

 struct ProductResponse: Codable {
    let code: String
    let product: Product
    let statusVerbose: String
    let status: Int

    enum CodingKeys: String, CodingKey {
        case code, product
        case statusVerbose = "status_verbose"
        case status
    }
}

struct Product: Codable {
    let code: String
    let productName: String

    enum CodingKeys: String, CodingKey {
        case code
        case productName = "product_name"
    }

}


class ViewController: UIViewController {
    //var products = [Product]()
    let API_URL = "https://carsdata/api/v0/product/5000112630794.json"
    override func viewDidLoad() {
        super.viewDidLoad()
        Alamofire.request(API_URL).responseJSON {
            response in
            let json = response.data
            do
            {
                let decoder = JSONDecoder()
                let productData = try decoder.decode(ProductResponse.self, from: json!)
                for product in productData{  print(product.productName!) } }
            catch
                let err{  print(err) }
        }
    }
}
4

1 回答 1

-1

问题是您没有解析 JSON。你在这里有两个对象。ProductResponse并且Product您正试图将其解析为一个。productName是其中的一部分,Product但您正试图从中获取它ProductResponse。为清楚起见,我建议您创建 2 个实体并尝试以下操作:

struct ProductResponse: Codable {
    let code: String
    let product: Product
    let statusVerbose: String
    let status: Int

    enum CodingKeys: String, CodingKey {
        case code, product
        case statusVerbose = "status_verbose"
        case status
    }
}

struct Product: Codable {
    let code: String
    let productName: String

    enum CodingKeys: String, CodingKey {
        case code
        case productName = "product_name"
    }
}

并尝试解码ProductResponse.self

于 2019-02-24T22:07:36.257 回答