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
    }
}
相关推荐
1024小神2 小时前
swift中 列表、字典、集合、元祖 常用的方法
数据结构·算法·swift
如此风景2 小时前
SwiftUI 状态管理详解
ios
QuantumLeap丶2 小时前
《Flutter全栈开发实战指南:从零到高级》- 25 -性能优化
android·flutter·ios
游戏开发爱好者85 小时前
H5 混合应用加密 Web 资源暴露到 IPA 层防护的完整技术方案
android·前端·ios·小程序·uni-app·iphone·webview
2501_915106326 小时前
最新版本iOS系统设备管理功能全面指南
android·macos·ios·小程序·uni-app·cocoa·iphone
游戏开发爱好者86 小时前
HTTPS DDoS 排查 异常流量到抓包分析
网络协议·ios·小程序·https·uni-app·iphone·ddos
TouchWorld7 小时前
iOS逆向-哔哩哔哩增加3倍速播放(3)-[横屏视频-全屏播放]场景
ios·swift
2501_915918417 小时前
iOS 性能监控 运行时指标与系统行为的多工具协同方案
android·macos·ios·小程序·uni-app·cocoa·iphone
00后程序员张8 小时前
IPA 混淆技术全解,从成品包结构出发的 iOS 应用安全实践与工具组合
android·安全·ios·小程序·uni-app·cocoa·iphone