티스토리 뷰
Codable
자신을 외부 표현(JSON) 으로 변환(Encode) 하거나 외부 표현(JSON) 으로부터 변환(Decode) 할 수 있는 타입으로
Encodable & Decodable 로 구성된 유니온 타입 프로토콜
Encoding
Person 객체를 Codable 채택 후 JSON 으로 인코딩
struct Person: Codable {
let name: String
let age: Int
}
let a = Person(name: "kim", age: 19)
do {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try encoder.encode(a)
if let jsonString = String(data: data, encoding: .utf8) {
print(jsonString)
}
} catch {
print(error)
}

Decoding
JSON 을 Person 객체로 디코딩
let jsonData = """
{
"name" : "jmkim",
"age" : 30
}
""".data(using: .utf8)!
struct Person: Codable {
let name: String
let age: Int
}
do {
let decoder = JSONDecoder()
let data = try decoder.decode(Person.self, from: jsonData)
print(data)
} catch {
print(error)
}

CodingKey
JSON 의 키값, 객체의 변수명이 다를 경우 CodingKey를 사용해서 key 를 매핑해줄 수 있다.
let jsonData = """
{
"name" : "jmkim",
"age" : 30,
"birth_date" : "1993-10-31"
}
""".data(using: .utf8)!
struct Person: Codable {
let name: String
let age: Int
let birthDate: String
enum CodingKeys: String, CodingKey {
case name
case age
case birthDate = "birth_date"
}
}
do {
let decoder = JSONDecoder()
let data = try decoder.decode(Person.self, from: jsonData)
print(data)
} catch {
print(error)
}

Reference
'IOS > swift' 카테고리의 다른 글
| [Swift] Method Dispatch 와 성능 최적화 (0) | 2022.04.05 |
|---|---|
| [Swift] Optional (0) | 2022.03.22 |
| Property wrapper (UserDefaults 적용) (0) | 2022.03.05 |
| Result Type (0) | 2022.03.03 |
| [Swift] lazy (0) | 2022.03.01 |