繁体   English   中英

如何使用 Swift 为 JSON 数据创建 JSON Codable 和 Decodable?

[英]How to create JSON Codable and Decodable for a JSON data using Swift?

在我的场景中,我试图在 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
}

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

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

以下将是解析您的 JSON 的模型,另外我强烈建议您使用以下网站来创建您的 json 模型,而不是自己尝试以避免错误

https://app.quicktype.io/

import Foundation

// MARK: - JSONModelElement
struct JSONModelElement: Codable {
    let id, name, gender, jsonModelClass: String
    let club, persona, crush, breastSize: String
    let strength, hairstyle, color: String
    let stockings: Stockings
    let accessory, scheduleTime, scheduleDestination, scheduleAction: String

    enum CodingKeys: String, CodingKey {
        case id = "ID"
        case name = "Name"
        case gender = "Gender"
        case jsonModelClass = "Class"
        case club = "Club"
        case persona = "Persona"
        case crush = "Crush"
        case breastSize = "BreastSize"
        case strength = "Strength"
        case hairstyle = "Hairstyle"
        case color = "Color"
        case stockings = "Stockings"
        case accessory = "Accessory"
        case scheduleTime = "ScheduleTime"
        case scheduleDestination = "ScheduleDestination"
        case scheduleAction = "ScheduleAction"
    }
}

enum Stockings: String, Codable {
    case loose = "Loose"
    case none = "None"
    case osana = "Osana"
}

typealias JSONModel = [JSONModelElement]

// 使用一行传递 JSON。

let students = try JSONDecoder().decode(JSONModel.self, from: data)

您可以使用此代码:

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 {
                    let students = try? JSONDecoder().decode(ModelAPI.self, from: data)
                    students?.forEach {
                        print($0.id)
                    }
                }
            }
        }.resume()
    }
}

你的班:

import Foundation

class ModelAPIElement: Codable {
    let id, name, gender, modelAPIClass: String?
    let club, persona, crush, breastSize: String?
    let strength, hairstyle, color: String?
    let stockings: Stockings?
    let accessory, scheduleTime, scheduleDestination, scheduleAction: String?

    enum CodingKeys: String, CodingKey {
        case id = "ID"
        case name = "Name"
        case gender = "Gender"
        case modelAPIClass = "Class"
        case club = "Club"
        case persona = "Persona"
        case crush = "Crush"
        case breastSize = "BreastSize"
        case strength = "Strength"
        case hairstyle = "Hairstyle"
        case color = "Color"
        case stockings = "Stockings"
        case accessory = "Accessory"
        case scheduleTime = "ScheduleTime"
        case scheduleDestination = "ScheduleDestination"
        case scheduleAction = "ScheduleAction"
    }

    init(id: String?, name: String?, gender: String?, modelAPIClass: String?, club: String?, persona: String?, crush: String?, breastSize: String?, strength: String?, hairstyle: String?, color: String?, stockings: Stockings?, accessory: String?, scheduleTime: String?, scheduleDestination: String?, scheduleAction: String?) {
        self.id = id
        self.name = name
        self.gender = gender
        self.modelAPIClass = modelAPIClass
        self.club = club
        self.persona = persona
        self.crush = crush
        self.breastSize = breastSize
        self.strength = strength
        self.hairstyle = hairstyle
        self.color = color
        self.stockings = stockings
        self.accessory = accessory
        self.scheduleTime = scheduleTime
        self.scheduleDestination = scheduleDestination
        self.scheduleAction = scheduleAction
    }
}

enum Stockings: String, Codable {
    case loose = "Loose"
    case none = "None"
    case osana = "Osana"
}

typealias ModelAPI = [ModelAPIElement]

更新:或结构

import Foundation

struct ModelAPIElement: Codable {
    let id, name, gender, modelAPIClass: String?
    let club, persona, crush, breastSize: String?
    let strength, hairstyle, color: String?
    let stockings: Stockings?
    let accessory, scheduleTime, scheduleDestination, scheduleAction: String?

    enum CodingKeys: String, CodingKey {
        case id = "ID"
        case name = "Name"
        case gender = "Gender"
        case modelAPIClass = "Class"
        case club = "Club"
        case persona = "Persona"
        case crush = "Crush"
        case breastSize = "BreastSize"
        case strength = "Strength"
        case hairstyle = "Hairstyle"
        case color = "Color"
        case stockings = "Stockings"
        case accessory = "Accessory"
        case scheduleTime = "ScheduleTime"
        case scheduleDestination = "ScheduleDestination"
        case scheduleAction = "ScheduleAction"
    }
}

enum Stockings: String, Codable {
    case loose = "Loose"
    case none = "None"
    case osana = "Osana"
}

typealias ModelAPI = [ModelAPIElement]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM