typealias Codable = Encodable & Decodable struct Employee: Codable { var name:String var id: Int var mToy:Toy } struct Toy:Codable { var name:String } extension Employee:CustomStringConvertible { var description: String { return name + "(" + String(id) + "): " + mToy.name } } /// encode instance to jsonString let toyA = Toy(name: "Teddy Bear") let employeeA = Employee(name: "EmployA", id:1, mToy:toyA) let jsonEncoder = JSONEncoder() let jsonData = try? jsonEncoder.encode(employeeA) // Xcode omits jsonData and only provides the number of bytes in jsonData // jsonData contains an unreadable representation of employeeA print("jsonData: \(jsonData)") let jsonString = String(data: jsonData!, encoding: .utf8) print("jsonString: \(jsonString)") /// decode jsonString to instance let jsonDecoder = JSONDecoder() let employeeADecoded = try? jsonDecoder.decode(Employee.self, from: jsonData!) print(employeeADecoded!)
//result
/*
jsonData: Optional(54 bytes)
jsonString: Optional("{\"name\":\"EmployA\",\"id\":1,\"mToy\":{\"name\":\"Teddy Bear\"}}")
EmployA(1): Teddy Bear
*/
假设,现在后台改接口了
from : {\"name\":\"EmployA\",\"id\":1,\"mToy\":{\"name\":\"Teddy Bear\"}}
to : {\"name\":\"EmployA\",\"gift\":\"Teddy Bear\",\"emplyeeID\":1}
需要实现encoding 和 decoding的逻辑。
encode 需要实现 encode(to: Encoder) throws
decode 需要实现 init(from decoder: Decoder) throws
//typealias Codable = Encodable & Decodable struct Employee{ var name:String var id: Int var mToy:Toy enum CodingKeys: String, CodingKey{ case id = "emplyeeID" case name case gift } } extension Employee: Encodable { func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(name, forKey: .name) try container.encode(id, forKey: .id) try container.encode(mToy.name, forKey: .gift) } } extension Employee:Decodable { init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) name = try values.decode(String.self, forKey: .name) id = try values.decode(Int.self, forKey: .id) let gift = try values.decode(String.self, forKey: .gift) mToy = Toy(name: gift) } } extension Employee:CustomStringConvertible { var description: String { return name + "(" + String(id) + "): " + mToy.name } } struct Toy{ var name:String }