-1

我在这里有一个问题...我正在使用 WooCommerce API 从数据库中获取数据...这段代码一切都很好,但是我在获取特色照片(featured_src)时遇到了一个奇怪的问题,特色照片值是一个字符串,当产品图像存在,但是当没有产品图像时,我得到一个布尔值而不是字符串(我得到一个错误)。应用程序崩溃。正如您在我的代码中看到的,我将属性指定为 String 或 int 或....并且我将 features_src 设置为字符串,但有时我会得到一个 bool 值。我应该如何编辑我的代码?

import UIKit

struct Products: Decodable {
let products: [product]
}

struct product: Decodable {

let title: String
let id: Int
let price: String
let sale_price: String?
let featured_src: String?
let short_description: String
 }


class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    let jsonUrlString = "https://www.komeil24.com/wc-api/v3/products"

    guard let url = URL(string: jsonUrlString) else {return}

    URLSession.shared.dataTask(with: url) { (data, response, error) in

        guard let data = data else {return}

        do {

            let products = try JSONDecoder().decode(Products.self, from: data)
            print(products.products)

        } catch let jsonErr {

          print("Error" , jsonErr)
        }

    }.resume()

}

}
4

1 回答 1

0

服务器对此进行了可怕的编码。但是作为开发人员,我们必须使用我们所获得的东西。您将不得不Product手动解码。另外,我认为feature_src更接近 aURL?而不是 a String?(如果你愿意,你可以改变它)。

此处的关键要点是,try decoder.decode(URL.self, ...)如果密钥不包含 a URL,则不要使用并获取错误,而是使用try? decoder.decode(URL.self, ...)并获取 a nil

struct Product: Decodable {
    let title: String
    let id: Int
    let price: String
    let salePrice: String?
    let featuredSource: URL?
    let shortDescription: String

    private enum CodingKeys: String, CodingKey {
        case title, id, price
        case salePrice = "sale_price"
        case featuredSource = "featured_src"
        case shortDescription = "short_description"
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        // Nothing special here, just typical manual decoding
        title            = try container.decode(String.self, forKey: .title)
        id               = try container.decode(Int.self, forKey: .id)
        price            = try container.decode(String.self, forKey: .price)
        salePrice        = try container.decodeIfPresent(String.self, forKey: .salePrice)
        shortDescription = try container.decode(String.self, forKey: .shortDescription)

        // Notice that we use try? instead of try
        featuredSource   = try? container.decode(URL.self, forKey: .featuredSource)
    }
}
于 2018-03-31T15:57:45.293 回答