如何從 JSON 文件構建模型

勒內塔羅牌

這是我第一次在 Swift 中使用 JSON,當我嘗試使用我的模型解析文件時,出現此錯誤:

給定的數據不是有效的 JSON。

我認為問題在於我如何做我的模型。

我解析JSON的方式:

import SwiftUI

struct EmergencyView: View {
    let emergency: [EmergencyNumberModel]
    init() {
        let url = Bundle.main.url(forResource: "emergency",
                                  withExtension: "json")!
        let data = try! Data(contentsOf: url)
        emergency = try! JSONDecoder().decode([EmergencyNumberModel].self, from: data) //Error
    }
    
    var body: some View {
        List(emergency, id: \.id) { emer in
            
            if emer.Country != nil {
                Label(emer.Country, systemImage: "quote.bubble")
                    .font(.headline)
            } else{
                Text(emer.Country)
            }
        }
        navigationTitle("Emergency")
    }
}

這是我使用的 JSON 的一小部分,“emergency.json”:

[
  {
    "Country": {
      "Name": "Afghanistan",
      "ISOCode": "AF",
      "ISONumeric": "4"
    },
    "Ambulance": {
      "All": [
        "112"
      ]
    },
    "Fire": {
      "All": [
        "119"
      ]
    },
    "Police": {
      "All": [
        "119"
      ]
    },
    "Dispatch": {
      "All": [
        null
      ]
    },
    "Member_112": false,
    "LocalOnly": true,
    "Notes": false
  },
 
 .
 .
 .

]

這是我的模型,“EmergencyNumberModel.swift”:

struct EmergencyNumberModel: Codable, Identifiable {
    var id = UUID()
    let Country: String
    let Ambulance: String
    let Fire: String
    let Police: String
    let Dispatch: String
}

我的模型中是否需要其他變量來訪問內部鍵或變量的數據類型錯誤?

工作犬

使用https://app.quicktype.io/生成 swift 結構,這是使用 json 數據的一種基本方法:

struct EmergencyView: View {
    @State var emergencies: [EmergencyModel] = []  // <--- here
    
    var body: some View {
        List(emergencies) { emer in
            if emer.country.name.isEmpty {
                Text("no country name")
            } else {
                Label(emer.country.name, systemImage: "quote.bubble").font(.headline)
            }
        }
        .onAppear {
            if let emrgncy = loadData(from: "emergency") {  // <--- here
                emergencies = emrgncy
            }
        }
    }
    
    func loadData(from file: String) -> [EmergencyModel]? {
        do {
            if let filePath = Bundle.main.path(forResource: file, ofType: "json") {
                let data = try Data(contentsOf: URL(fileURLWithPath: filePath))
                let results = try JSONDecoder().decode([EmergencyModel].self, from: data)
                return results
            }
        } catch {
            print("----> error: \(error)") // <-- todo, deal with errors
        }
        return nil
    }
    
}

struct EmergencyModel: Identifiable, Codable {
    let id = UUID()  // <--- here
    let country: Country
    let ambulance, fire, police: Ambulance
    let dispatch: Dispatch
    let member112, localOnly, notes: Bool
    
    enum CodingKeys: String, CodingKey {
        case country = "Country"
        case ambulance = "Ambulance"
        case fire = "Fire"
        case police = "Police"
        case dispatch = "Dispatch"
        case member112 = "Member_112"
        case localOnly = "LocalOnly"
        case notes = "Notes"
    }
}

struct Ambulance: Codable {
    let all: [String]
    
    enum CodingKeys: String, CodingKey {
        case all = "All"
    }
}

struct Country: Codable {
    let name, isoCode, isoNumeric: String
    
    enum CodingKeys: String, CodingKey {
        case name = "Name"
        case isoCode = "ISOCode"
        case isoNumeric = "ISONumeric"
    }
}

struct Dispatch: Codable {
    let all: [JSONNull?]
    
    enum CodingKeys: String, CodingKey {
        case all = "All"
    }
}

class JSONNull: Codable, Hashable {
    
    public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool {
        return true
    }
    
    func hash(into hasher: inout Hasher) {
       hasher.combine(0)
    }
    
    public init() {}
    
    public required init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if !container.decodeNil() {
            throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull"))
        }
    }
    
    public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encodeNil()
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Pyspark:從 JSON 文件創建模式

Django:如何根据 json 文件中的数据创建模型的实例?

如何從 JSON 文件中向用戶發送消息?

如何從 Python 中的 JSON 文件調用 UDF?

如何從 JSON 文件中讀取特定值?

如何從 json 文件導入數組?

如何从CSV文件创建模型实例

如何从json字典自动创建模型类(NSObject)?

如何从 C# 中的 JSON 密钥创建模型?

如何從 CSV 形成 JSON

Flutter:如何將“模型實例”從 json_serializable 包含到 http 帖子正文?

Rails:如何从sql文件自动创建模型

如何在 .py 文件中创建模型实例?

如何使用python將數據從csv文件添加到json鍵中

如何根據 json 文件從 Redis 排序集中刪除項目

如何從 Nestjs 中的 URL 將數據下載到 JSON 文件中?

如何從 R 中復雜的嵌套 .json 文件中提取元素?

如何從回調返回 json 消息而不是觸發錯誤 | NestJs 文件上傳

如何根據嵌套值從 json 文件中提取對象(使用 JavaScript)

为JSON创建模型

使用 Swifty JSon 模型创建模型

如何从json文件创建余烬模型

如何为以下JSON数据创建模型类并进行解析?

如何使用 Angularjs 2 中的接口为复杂的 JSON 对象创建模型

如何为动态键,json解析,swift5创建模型

如何建模所需的 json 结构

如何使用 Spark Scala 从 JSON 文件为字段子集创建模式?

如何在Croogo cms中创建模型,控制器和查看文件?

如何從文件傳遞參數?