如何符合Swift 4中的序列协议

时间:2019-02-24 21:55:34

标签: swift swift4 json-deserialization jsondecoder parsing-error

当前试图快速将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) }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

问题是您没有解析JSON。您在这里有两个对象。 ProductResponseProduct,您正在尝试将其解析为一个。 productNameProduct的一部分,但您正在尝试从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