在 Swift 中解码 JSON 4

Decoding JSON in Swift 4

我正在阅读 Apple 应用程序开发指南,这是我现在正在使用的代码...

struct CategoryInfo: Codable {
    var category: String
    var description: String
    var logo: String
    var mobileCategoryName: String

    enum Keys: String, CodingKey {
        case category
        case description = "descr"
        case logo
        case mobileCategoryName = "mobileCatName"
    }

    init(from decoder: Decoder) throws {
        let valueContainer = try decoder.container(keyedBy: Keys.self)
        self.category = try valueContainer.decode(String.self, forKey: Keys.category)
        self.description = try valueContainer.decode(String.self, forKey: Keys.description)
        self.logo = try valueContainer.decode(String.self, forKey: Keys.logo)
        self.mobileCategoryName = try valueContainer.decode(String.self, forKey: Keys.mobileCategoryName)
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    let categories = Industry_TableViewController()
    categories.fetchCategoryInfo { (category) in
        if let category = category {
            print(category)
        }
    }
}

func fetchCategoryInfo(completion: @escaping(CategoryInfo?) -> Void) {
    let url = URL(string: "XXXXX")!        
    let task = URLSession.shared.dataTask(with: url) {
        (data, response, error) in
        let jsonDecoder = JSONDecoder()
        if let data = data,
            let category = try? jsonDecoder.decode(CategoryInfo.self, from: data) {
                completion(category)
            } else {
                print("Nothing reutrned or Not decoded")
                completion(nil)
            }
    }
    task.resume()
}

当我返回的 JSON 采用以下格式时它工作正常...

{"category":"Excavators","descr":"Compact, Mid-Sized, Large, Wheeled, Tracked...","logo":"excavators","mobileCatName":"Excavators"}

我的结构已创建并且所有变量都已正确填充。但是 API 不会一次带回一个类别,而是像这样带回多个类别...

[{"category":"Aerial Lifts","descr":"Aerial Lifts, Man Lifts, Scissor Lifts...","logo":"aeriallifts","mobileCatName":"Aerial Lifts"},{"category":"Aggregate Equipment","descr":"Crushing, Screening, Conveyors, Feeders and Stackers...","logo":"aggregateequipment","mobileCatName":"Aggregate"},{"category":"Agricultural Equipment","descr":"Tractors, Harvesters, Combines, Tillers...","logo":"agricultural","mobileCatName":"Agricultural"}]

我 运行 陷入困境,试图弄清楚如何正确解码。我已经走了很多路,我什至不知道该寻找什么了。谁能帮我指明方向。

试试? jsonDecoder.decode([CategoryInfo].self, 来自: 数据)

您需要修改函数以解析一组类别而不是单个类别。您只需要将 Array<CategoryInfo> 元类型传递给 decode 函数并修改函数签名,以便完成处理程序也 returns 一个数组。

func fetchCategoryInfo(completion: @escaping ([CategoryInfo]?) -> Void) {
    let url = URL(string: "XXXXX")!        
    let task = URLSession.shared.dataTask(with: url) {
        (data, response, error) in
        let jsonDecoder = JSONDecoder()
        if let data = data,
            let categories = try? jsonDecoder.decode([CategoryInfo].self, from: data) {
                completion(categories)
            } else {
                print("Nothing reutrned or Not decoded")
                completion(nil)
            }
    }
    task.resume()
}