티스토리 뷰

IOS/swift

[Swift] Codable

내일도이렇게 2022. 3. 22. 15:58

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 

https://medium.com/humanscape-tech/swift%EC%97%90%EC%84%9C-codable-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0-367587c5a591

'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
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함