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
    }
}
相关推荐
初级代码游戏1 天前
iOS只剩美工了吗?时间都被遮盖看不清了
ios·界面设计·美工
2501_915918411 天前
iOS 开发中证书创建与管理中的常见问题
android·ios·小程序·https·uni-app·iphone·webview
00后程序员张1 天前
IOScer 开发环境证书包括哪些,证书、描述文件与 App ID 的协同管理实践
android·ios·小程序·https·uni-app·iphone·webview
江东小bug王1 天前
深入理解 UITabBarController:代理方法与 ViewController 生命周期的执行顺序(含 UINavigationController 场景)
ios
阿里云云原生1 天前
RUM 赋能 iOS App 稳定:从异常体系到监控方案的全方位解析!
ios·云原生
Zfox_1 天前
无缝穿越系统边界:节点小宝4.0如何让我的Mac/iOS像访问本地盘一样操控Windows
windows·macos·ios·节点小宝
Zender Han1 天前
Flutter 图片裁剪插件 image_cropper 最新版介绍与使用教程
android·flutter·ios
方白羽1 天前
Android 与 iOS 动态更换应用图标实现方案
android·ios·app
Haha_bj2 天前
Swift——高阶函数(map、filter、reduce、forEach、sorted、contains……)
ios·app·swift
妮妮分享2 天前
维智地图如何集成
开发语言·ios·swift