Codable协议
1. 基本概念
2. 使用方式
import Foundation
struct User: Codable {
let id: Int
let name: String
let email: String?
}3. 处理复杂数据
4. 自定义编码和解码
5. 小结
Last updated
import Foundation
struct User: Codable {
let id: Int
let name: String
let email: String?
}Last updated
let user = User(id: 1, name: "Alice", email: "alice@example.com")
do {
let jsonData = try JSONEncoder().encode(user)
let jsonString = String(data: jsonData, encoding: .utf8)!
print(jsonString)
} catch {
print("Error encoding JSON: \(error)")
}let jsonString = """
{
"id": 1,
"name": "Alice",
"email": "alice@example.com"
}
"""
if let jsonData = jsonString.data(using: .utf8) {
do {
let user = try JSONDecoder().decode(User.self, from: jsonData)
print(user)
} catch {
print("Error decoding JSON: \(error)")
}
}struct Group: Codable {
let groupName: String
let members: [User]
}
let jsonString = """
{
"groupName": "Developers",
"members": [
{"id": 1, "name": "Alice", "email": "alice@example.com"},
{"id": 2, "name": "Bob", "email": "bob@example.com"}
]
}
"""
if let jsonData = jsonString.data(using: .utf8) {
do {
let group = try JSONDecoder().decode(Group.self, from: jsonData)
print(group)
} catch {
print("Error decoding JSON: \(error)")
}
}struct User: Codable {
let id: Int
let name: String
enum CodingKeys: String, CodingKey {
case id
case name = "userName" // 将 "userName" 映射到 `name` 属性
}
}