当前试图快速将json字典解析到屏幕上,但是我遇到了此序列协议错误,还遇到类型不匹配错误,该错误获取字符串/数据并需要一个Int。错误是“类型'ProductResponse'与协议'序列'不符”和
“ 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) }
}
}
}
答案 0 :(得分:0)
问题是您没有解析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
。