推荐答案
在 Swift 中,Encodable 和 Decodable 是用于数据编码和解码的协议。Encodable 协议允许将对象编码为外部表示(如 JSON),而 Decodable 协议允许从外部表示(如 JSON)解码为对象。通常,这两个协议会一起使用,Swift 提供了一个组合协议 Codable,它是 Encodable 和 Decodable 的类型别名。
示例代码
// www.javascriptcn.com code example
import Foundation
struct User: Codable {
var name: String
var age: Int
}
// 编码
let user = User(name: "John", age: 30)
let encoder = JSONEncoder()
if let encodedData = try? encoder.encode(user) {
if let jsonString = String(data: encodedData, encoding: .utf8) {
print("Encoded JSON: \(jsonString)")
}
}
// 解码
let jsonString = """
{
"name": "Jane",
"age": 25
}
"""
if let jsonData = jsonString.data(using: .utf8) {
let decoder = JSONDecoder()
if let decodedUser = try? decoder.decode(User.self, from: jsonData) {
print("Decoded User: \(decodedUser)")
}
}输出
Encoded JSON: {"name":"John","age":30}
Decoded User: User(name: "Jane", age: 25)本题详细解读
Encodable 协议
Encodable 协议定义了一个方法 encode(to:),用于将对象编码为外部表示。通常,外部表示是 JSON 格式,但也可以是其他格式,如 Property List 或 XML。
func encode(to encoder: Encoder) throws
Decodable 协议
Decodable 协议定义了一个初始化方法 init(from:),用于从外部表示解码为对象。
init(from decoder: Decoder) throws
Codable 协议
Codable 是 Encodable 和 Decodable 的类型别名,通常用于同时支持编码和解码的场景。
typealias Codable = Encodable & Decodable
使用 JSONEncoder 和 JSONDecoder
JSONEncoder 和 JSONDecoder 是 Swift 提供的用于 JSON 编码和解码的工具类。JSONEncoder 可以将 Encodable 对象编码为 JSON 数据,而 JSONDecoder 可以将 JSON 数据解码为 Decodable 对象。
自定义编码和解码
在某些情况下,你可能需要自定义编码和解码的行为。可以通过实现 Encodable 和 Decodable 协议中的方法来达到这一目的。
// www.javascriptcn.com code example
struct CustomUser: Codable {
var name: String
var age: Int
enum CodingKeys: String, CodingKey {
case name = "user_name"
case age = "user_age"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
age = try container.decode(Int.self, forKey: .age)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(age, forKey: .age)
}
}注意事项
- 确保所有需要编码和解码的属性都遵循
Codable协议。 - 如果 JSON 中的键与 Swift 中的属性名不一致,可以使用
CodingKeys枚举来映射键名。 - 处理可选值时,确保在解码时处理可能的
nil值。