簡體   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