四海一家中华亲 發表於 2023-9-12 11:06:39

Swift使用编解码库Codable的过程详解

<div id="navCategory"><h5 class="catalogue">目录</h5><ul class="first_class_ul"><li>Codable协议定义</li><li>JSON 和 模型的相互转换</li><li>字典 和 模型的相互转换</li></ul></div><p>Codable 是 Swift 引入的全新的编解码库,使开发者更方便的解析JSON 或 plist 文件。支持枚举、结构体和类。</p>
<p class="maodian"></p><h2>Codable协议定义</h2>
<p>Codable代表一个同时符合 Decodable 和 Encodable 协议的类型,即可解码且可编码的类型。</p>
<div class="jb51code"><pre class="brush:java;">typealias Codable = Decodable &amp; Encodable
public protocol Decodable {
    public init(from decoder: Decoder) throws
}
public protocol Encodable {
    public func encode(to encoder: Encoder) throws
}</pre></div>
<p>Codable从 Swift 4 开始引入,包含了 Encoder 和 Decoder 协议和他们的两个实现 JSONEncoder、JSONDecoder 和 PropertyListEncoder、PropertyListDecoder。</p>
<p>其中 Codable 及其相关协议放在了标准库中,而具体的 Encoder、Decoder 类放在了 Foundation 框架中。&nbsp;</p>
<p class="maodian"></p><h2>JSON 和 模型的相互转换</h2>
<p>苹果提供了&nbsp; <code>JSONEncoder </code>&nbsp;和&nbsp; <code>JSONDecoder </code>&nbsp;这两个结构体来方便得在 JSON 数据和自定义模型之间互相转换。苹果可以利用一些系统私有的机制来实现转换,而不需要通过&nbsp; <code>OC Runtime </code>。</p>
<p>只要让自己的数据类型符合 Codable 协议,就可以用系统提供的编解码器进行编解码。</p>
<div class="jb51code"><pre class="brush:java;">struct User: Codable {
    var name: String
    var age: Int
}</pre></div>
<p>解码(JSON Data -&gt; Model):</p>
<div class="jb51code"><pre class="brush:json;">let user = JSONDecoder().decode(User.self, from: jsonData)</pre></div>
<p>编码(Model -&gt; JSON Data):</p>
<div class="jb51code"><pre class="brush:json;">let jsonData = JSONEncoder().encode(user)</pre></div>
<p class="maodian"></p><h2>字典 和 模型的相互转换</h2>
<p>将模型用JSONEncoder的encode转成Data,然后再用JSONSerialization反序列化成Dictionary对象。</p>
<div class="jb51code"><pre class="brush:java;">struct User: Codable {
    var name: String?
    var age: Int?
    static func convertFromDict(dict: NSDictionary) -&gt; 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() -&gt; 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
    }
}</pre></div>
<p>到此这篇关于Swift使用编解码库Codable的文章就介绍到这了,更多相关Swift编解码库Codable内容请搜索琼殿技术社区以前的文章或继续浏览下面的相关文章希望大家以后多多支持琼殿技术社区!</p>
                           
                            <div class="art_xg">
                              <b>您可能感兴趣的文章:</b><ul><li>swift语言Codable 用法及原理详解</li><li>Swift利用Decodable解析JSON的一个小问题详解</li><li>关于Swift 4.1中的Codable改进详解</li></ul>
                            </div>

                        </div>
                        <!--endmain-->
頁: [1]
查看完整版本: Swift使用编解码库Codable的过程详解