json - 在 Swift 4 中解码 JSON

标签 json swift codable

我正在阅读 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"}]

我在试图弄清楚如何正确解码它时遇到了困难。我走了很多条路,我什至不知道该再寻找什么。任何人都可以帮助我或为我指明方向吗?

最佳答案

您需要修改函数来解析一组类别而不是单个类别。您只需要通过 Array<CategoryInfo> decode 的元类型函数并修改函数签名,以便完成处理程序也返回一个数组。

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()
}

关于json - 在 Swift 4 中解码 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53159586/

相关文章:

ios - 如果 Swift 的 .sort( ) 方法的底层算法通常是稳定的,为什么它不能保证稳定性?

ios - 使用 Codable、swift 4 解析 JSON

swift - 如果我想从 Codable 中排除一些属性,为什么这些属性必须是可选的?

android,无需遍历所有位置即可找到最近的位置

java - 将 Json-Array 的 20 个对象拆分为单独的单个数组 json 文件?

javascript - 自动完成 json 数据

ios - GIDSignInButton - 以 NSException 类型的未捕获异常终止

json - REST API 最佳实践 : args in query string vs in request body

swift - 我在使用 Swift 2.0 接收用户当前位置时遇到困难

json - 如何使用 Codable 协议(protocol)快速构建 json 对象模型