【问题标题】:Issue With Using JSON Decode for Swift 4 XcodeSwift 4 Xcode 使用 JSON 解码的问题
【发布时间】:2018-03-31 09:24:17
【问题描述】:

我有一个问题...我正在使用 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()

}

}

【问题讨论】:

  • 你必须编写一个自定义的初始化器来有条件地处理这种情况。
  • 需要用正确的句子进行更多说明。

标签: xcode swift4 jsondecoder


【解决方案1】:

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

这里的关键要点是,如果密钥不包含URL,则不要使用try decoder.decode(URL.self, ...) 并得到错误,而是使用try? decoder.decode(URL.self, ...) 并得到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)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-14
    相关资源
    最近更新 更多