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
    }
}
相关推荐
感谢地心引力40 分钟前
安卓、苹果手机无线投屏到Windows
android·windows·ios·智能手机·安卓·苹果·投屏
2501_9159184112 小时前
HTTPS 代理失效,启用双向认证(mTLS)的 iOS 应用网络怎么抓包调试
android·网络·ios·小程序·https·uni-app·iphone
Swift社区12 小时前
Flutter 路由系统,对比 RN / Web / iOS 有什么本质不同?
前端·flutter·ios
zhyongrui12 小时前
SnipTrip 发热优化实战:从 60Hz 到 30Hz 的性能之旅
ios·swiftui·swift
Andy Dennis12 小时前
ios开发 xcode配置
ios·cocoa·xcode
JoyCong199813 小时前
iOS 27 六大功能前瞻:折叠屏、AI Siri与“雪豹式”流畅体验,搭配ToDesk开启跨设备新协作
人工智能·ios·cocoa
linweidong13 小时前
屏幕尺寸的万花筒:如何在 iOS 碎片化生态中以不变应万变?
macos·ios·移动开发·objective-c·cocoa·ios面试·ios面经
Cestb0n13 小时前
iOS 逆向分析:东方财富请求头 em-clt-auth 与 qgqp-b-id 算法还原
python·算法·ios·金融·逆向安全
00后程序员张15 小时前
无需越狱,来对 iOS 设备进行调试、管理与分析
android·ios·小程序·https·uni-app·iphone·webview
00后程序员张15 小时前
在 iOS 上架中如何批量方便快捷管理 Bundle ID
android·ios·小程序·https·uni-app·iphone·webview