在 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/