ios - 将字典数组快速转换为自定义对象

标签 ios swift

我有:

    let countries : [[String : Any]] = [
            [
                "name" : "Afghanistan",
                "dial_code": "+93",
                "code": "AF"
            ],
            [
                "name": "Aland Islands",
                "dial_code": "+358",
                "code": "AX"
            ],
            [
                "name": "Albania",
                "dial_code": "+355",
                "code": "AL"
            ],
            [
                "name": "Algeria",
                "dial_code": "+213",
                "code": "DZ"
            ]
]

我想将所有这些字典数组添加到我的自定义对象中

let country:[Country] = countries

我的自定义对象如下所示:

class Country: NSObject {
        let name: String
        let dial_code : String
        let code: String

        init(name: String, dial_code: String, code: String) {
            self.name = name
            self.dial_code = dial_code
            self.code = code
        }
    }

我知道我需要一个遍历数组的循环,但我不知道下一步是什么。有一个例子会很棒。

最佳答案

你应该让你的国家符合Codable协议(protocol),使用 JSONSerialization 将您的字典转换为 JSON 数据然后解码 Data使用 JSONDecoder , 注意你可以设置它的 keyDecodingStrategy属性(property)convertFromSnakeCase自动避免需要声明自定义编码键,如 dial_Code :

struct Country: Codable {
    let name: String
    let dialCode : String
    let code: String
}

do {
    let json = try JSONSerialization.data(withJSONObject: countries)
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let decodedCountries = try decoder.decode([Country].self, from: json)
    decodedCountries.forEach{print($0)}
} catch {
    print(error)
}

Country(name: "Afghanistan", dialCode: "+93", code: "AF")

Country(name: "Aland Islands", dialCode: "+358", code: "AX")

Country(name: "Albania", dialCode: "+355", code: "AL")

Country(name: "Algeria", dialCode: "+213", code: "DZ")

关于ios - 将字典数组快速转换为自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47696778/

相关文章:

ios - 获取 Objective-C/IOS 中特定类的实例计数

swift - 表格 View 高度限制滚动

ios - 如何访问 UIImageView 以使用 Picker Controller 设置图像

ios - UIBarButtonItem 色调颜色 iOS4

iPhone ios线程问题: delegate object not responding when using dispatch_async

ios - SKAction.playSoundFileNamed -- 如何将音量设置在 0.0 - 1.0 之间

iphone - 我怎样才能设置 iphone 在预先安排的日期调用电话?

ios - 带按钮的 UICollectionView

swift - @objc、@class_protocol 和 :class in swift Swift 之间的区别

swift - 我想在按钮上使用 bool,如果我单击 imageview 的按钮图像已更改,如果再次单击按钮,则使用 Swift 反转图像