【问题标题】:Swift 4 Json Decoding, Which is the best/latest method, Using Codable or Decodable?Swift 4 Json 解码,哪个是最好/最新的方法,使用 Codable 还是 Decodable?
【发布时间】:2018-11-02 11:21:08
【问题描述】:

在 Swift 4.1 中,我们可以像这样解码 JSON:

struct Person: Decodable {
    let id: Int
    let name: String
    let imageUrl: String
}

let people = [Person]()

func parseJSON(data: Data) {
    do {
        let decoder = JSONDecoder()
        decoder.keyDecodingStratergy = .convertFromSnakeCase
        self.people = try decoder.decode([Person].self, from: data)
    } catch let error {
        print(error as? Any)
    }
}

第一季度。如果我使用Codable 而不是Decodable 有什么区别?哪个更好?

第二季度。在这里如何使用decodeIfPresent

第三季度。如果 JSON 中不存在key,如何解码?

【问题讨论】:

    标签: swift swift4 decodable


    【解决方案1】:

    在 Swift4 中编码和解码 JSON 的最佳方式

    这是一个简单对象 User 的 JSON 表示,让我们看看如何将这些数据反序列化为一个对象。

    {
    "id": 13,
    "firstname" : "John",
    "lastname" : "Doe",
    "email" : "john.doe@lost.com"
    }
    

    将 JSON 解码为对象

    我使用结构类型来表示我的对象并包含协议可解码以允许反序列化。

    struct User : Decodable {
     let id : Int
     let firstname : String
     let lastname : String
     let email : String
    }
    

    现在我们准备使用 JSONDecoder 对其进行解码。

    // 假设我们的数据来自服务器端

         let jsonString = "{ \"id\": 13, \"firstname\" : \"John\", \"lastname\" : \"Doe\", \"email\" : \"john.doe@lost.com\" }"
    
    
    
    let jsonData = jsonString.data(using: .utf8)!
    
        do {
           let jsonDecoder = JSONDecoder()
           let user = try jsonDecoder.decode(User.self, from: jsonData)
          print("Hello \(user.firstname) \(user.lastname)")
        } catch {
            print("Unexpected error: \(error).")
        }
    

    很简单吧?现在让我们看看如何序列化它。 将对象编码为 JSON

    首先,我们需要更新我们的结构以允许编码。为此,我们只需要包含协议 Encodable。

    struct User : Encodable, Decodable {
     ...
    }
    

    我们的对象已准备好被序列化回 JSON。我们遵循与之前相同的过程,这次使用 JSONEncoder。在这种情况下,我还将数据转换为字符串以确保它正常工作 // 假设我们有一个要序列化的对象

    这还是很简单的!那么 Codable 到底是什么? 好吧,Codable 只是 Encodable 和 Decodable 协议的别名,正如你在它的定义中看到的那样 公共类型别名 Codable = 可解码和可编码 如果您不希望您的 JSON 密钥驱动您的命名,您仍然可以使用 CodingKeys 自定义它们。描述为枚举,编码/解码时会自动拾取

        struct User : Codable {
         var id : Int
         var firstname : String
         var lastname : String
    var email : String?
    
    // keys
    private enum CodingKeys: String, CodingKey {
        case id = "user_id"
        case firstname = "first_name"
        case lastname = "family_name"
        case email = "email_address"
    }
    

    }

    走得更远

    https://medium.com/@phillfarrugia/encoding-and-decoding-json-with-swift-4-3832bf21c9a8

    https://benoitpasquier.com/encoding-decoding-json-swift4/

    第三题答案:https://www.calhoun.io/how-to-determine-if-a-json-key-has-been-set-to-null-or-not-provided/

    【讨论】:

      【解决方案2】:

      如果可能,请尝试发布分开的问题,这样更容易回答和阅读。


      对于您的第一个问题:Codable 是扩展 EncodableDecodable 的协议。

      Decodable 是将数据解析为模型。例如从 JSON 数据到结构。

      Encodable 是从您的模型中获取数据。

      可编码两者都包含。

      【讨论】:

        猜你喜欢
        • 2017-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多