目前正在尝试将 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) }
}
}
}