Swift使用编解码库Codable

Codable 是 Swift 引入的全新的编解码库,使开发者更方便的解析JSON 或 plist 文件。支持枚举、结构体和类。

Codable协议定义

Codable代表一个同时符合 Decodable 和 Encodable 协议的类型,即可解码且可编码的类型。

Swift 复制代码
typealias Codable = Decodable & Encodable

public protocol Decodable {
    public init(from decoder: Decoder) throws
}

public protocol Encodable {
    public func encode(to encoder: Encoder) throws
}

Codable从 Swift 4 开始引入,包含了 Encoder 和 Decoder 协议和他们的两个实现 JSONEncoder、JSONDecoder 和 PropertyListEncoder、PropertyListDecoder。

其中 Codable 及其相关协议放在了标准库中,而具体的 Encoder、Decoder 类放在了 Foundation 框架中。

JSON 和 模型的相互转换

苹果提供了 JSONEncoderJSONDecoder 这两个结构体来方便得在 JSON 数据和自定义模型之间互相转换。苹果可以利用一些系统私有的机制来实现转换,而不需要通过 OC Runtime

只要让自己的数据类型符合 Codable 协议,就可以用系统提供的编解码器进行编解码。

Swift 复制代码
struct User: Codable {
    var name: String
    var age: Int
}

解码(JSON Data -> Model):

Swift 复制代码
let user = JSONDecoder().decode(User.self, from: jsonData)

编码(Model -> JSON Data):

Swift 复制代码
let jsonData = JSONEncoder().encode(user)

字典 和 模型的相互转换

将模型用JSONEncoder的encode转成Data,然后再用JSONSerialization反序列化成Dictionary对象。

Swift 复制代码
struct User: Codable {
    var name: String?
    var age: Int?

    static func convertFromDict(dict: NSDictionary) -> User? {
        var user: User?
        do {
            let data = try JSONSerialization.data(withJSONObject: dict, options: [])
            let decoder = JSONDecoder()
            user = try decoder.decode(User.self, from: data)
        } catch {
            print(error)
        }
        return user
    }
    
    func convertToDict() -> NSDictionary? {
        var dict: NSDictionary?
        do {
            let encoder = JSONEncoder()
            let data = try encoder.encode(self)
            dict = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary
        } catch {
            print(error)
        }
        return dict
    }
}
相关推荐
2501_915106326 小时前
苹果App Store上架费用及流程全面解析
android·ios·小程序·https·uni-app·iphone·webview
Privasa-隐私实验室7 小时前
蓝牙-多设备调试效率翻倍:从手动折腾到全自动调试的完整落地流程
物联网·ios·智能家居·智能硬件·智能手表
黑科技iOS上架11 小时前
UnityiOS工程混淆能解决App Store4.3被拒么?
ios·审核
恋猫de小郭12 小时前
iPhone Duo 适配详解,需要改变的不止是布局模型
前端·flutter·ios
Digitally14 小时前
如何在不从 iCloud 删除的情况下从iPhone删除照片
ios·iphone·icloud
游戏开发爱好者81 天前
网络连接排查指南,谁在电脑后台偷跑流量,哪些程序在联网
网络协议·计算机网络·网络安全·ios·adb·https·udp
ii_best1 天前
安卓脚本/ios开发软件按键精灵实战:自动定位弹窗广告关闭按钮坐标的通用方案
android·ios·自动化
Behaviour1 天前
iPhone Duo 来了,苹果 Siri AI 接入定制 Gemini
人工智能·ios·语言模型·aigc·iphone
用户38034165882971 天前
手写 fMP4 muxer:从 ISO 14496-12 到能播的文件
ios·音视频开发
深念Y1 天前
iOS模拟器在无Metal的NVIDIA显卡环境下的可行性研究报告
服务器·ios·unix·pve·freebsd