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_915918411 天前
Web 前端可视化开发工具对比 低代码平台、可视化搭建工具、前端可视化编辑器与在线可视化开发环境的实战分析
前端·低代码·ios·小程序·uni-app·编辑器·iphone
2501_915106321 天前
iOS 使用记录和能耗监控实战,如何查看电池电量消耗、App 使用时长与性能数据(uni-app 开发调试必备指南)
android·ios·小程序·uni-app·cocoa·iphone·webview
凉白开<--1 天前
mardown-it 有序列表ios序号溢出解决办法
ios·vue
Digitally1 天前
如何将 iPhone 备份到电脑/PC 的前 5 种方法
ios·电脑·iphone
Swift社区1 天前
在企业内部分发 iOS App 时如何生成并使用 manifest.plist
macos·ios·cocoa
他们都不看好你,偏偏你最不争气1 天前
【iOS】push 和 present
ios
2501_916013742 天前
HTTPS 抓包难点分析,从端口到工具的实战应对
网络协议·http·ios·小程序·https·uni-app·iphone
2501_915918412 天前
uni-app 项目 iOS 上架效率优化 从工具选择到流程改进的实战经验
android·ios·小程序·uni-app·cocoa·iphone·webview
00后程序员张2 天前
如何在不同 iOS 设备上测试和上架 uni-app 应用 实战全流程解析
android·ios·小程序·https·uni-app·iphone·webview
wjm0410062 天前
ios面试八股文
ios·面试