<aside> 📌 목차
</aside>
Codable is a protocol in Swift that allows for easy encoding and decoding of data.
By conforming to the Codable protocol, a type can be encoded to and decoded from various formats, such as JSON or Property List. Codable is particularly useful when working with data from web APIs, as it allows for easy serialization and deserialization of JSON data.
To conform to the Codable protocol, a type must specify how its properties should be encoded and decoded. This can be done by implementing the CodingKey protocol, which defines how each property should be represented in the encoded data.
Overall, Codable is a powerful and convenient tool for working with data in Swift, making it easier to serialize and deserialize data in a type-safe and customizable way.
To decode data using Codable, you can use the JSONDecoder class. Here's an example of decoding JSON data:
struct Person: Codable {
let name: String
let age: Int
}
let json = """
{
"name": "John Smith",
"age": 42
}
""".data(using: .utf8)!
let decoder = JSONDecoder()
let person = try! decoder.decode(Person.self, from: json)
print(person.name) // Output: John Smith
print(person.age) // Output: 42
In this example, we define a Person struct that conforms to Codable. We then create a JSON string representing a Person object and convert it to a Data object. We then create a JSONDecoder instance and use it to decode the Data object into a Person object. Finally, we print out the name and age properties of the decoded Person object.
Here's an example of a simple JSON object:
<aside>
🚨 Decodable 객체 속성 타입은 기본적으로 Optional 로 정의하는게 바람직함
Optional 이 아니라면 해당 속성 Decoding 이 실패하면 객체 전체의 디코딩이 실패함 </aside>
jSON 키 이름과 Decodable 객체 속성 이름 불일치
속성명을 변경하던가, CodingKey 를 정의하여 사용
만약 CodingKeys 를 선언했다면, 디코딩할 모든 속성을 case 에 추가해주어야함
let json = """
{
"Age": 42
}
""".data(using: .utf8)!
struct Test: Decodable {
var age: Int
enum CodingKeys: String, CodingKey {
case age = "Age"
}
}