首页 > 解决方案 > 如何使用 Swift 为 JSON 数据创建 JSON Codable 和 Decodable?

问题描述

在 myscenario 中,我试图在 Stuct Codable 和 Decodable 的帮助下从 JSON 响应中获取数据。但是如果我使用下面的代码,我会遇到错误

Error:typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))

下面的代码

func jsonDataLoad() {
    if let url = URL(string: "https://api.myjson.com/bins/1e33oo") {
        URLSession.shared.dataTask(with: url) { data, response, error in
            if let data = data {
                do {
                    //Swift 2/3/Objective C
                    //let json = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
                    //print(json)
                    let student = try JSONDecoder().decode(RootElement.self, from: data)
                    print(student.gender)
                } catch let error {
                    print(error)
                }
            }
            }.resume()
    }
}

可编码结构

// MARK: - RootElement
struct RootElement: Decodable {
    let id, name, gender, welcomeClass: String
    let club, persona, crush, breastSize: String
    let strength, hairstyle, color: String
    let accessory, scheduleTime, scheduleDestination, scheduleAction: String
}

标签: iosjsonswift

解决方案


你的 json root 是一个数组而不是字典[RootElement].self

let students = try JSONDecoder().decode([RootElement].self, from: data)
students.forEach {
   print($0.id)
}

推荐阅读