【问题标题】:Decoding JSON in Swift 4在 Swift 4 中解码 JSON
【发布时间】:2018-11-05 17:48:52
【问题描述】:

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

我正碰壁,试图弄清楚如何正确解码。我已经走了很多路,我什至不知道该寻找什么了。任何人都可以帮助或指出一个方向。

【问题讨论】:

    标签: json swift codable


    【解决方案1】:

    您需要修改函数以解析类别数组而不是单个类别。您只需将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()
    }
    

    【讨论】:

      【解决方案2】:

      试试? jsonDecoder.decode([CategoryInfo].self, from: data)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-11
        • 1970-01-01
        • 2018-08-15
        • 2018-09-19
        相关资源
        最近更新 更多