DEV_Larva

Decodable, Encodable, Codable(CodingKey) 본문

SwiftUI & UIKit/Network

Decodable, Encodable, Codable(CodingKey)

NelchuPapa 2023. 11. 11. 15:43
반응형

Decodable

JSON과 같은 외부 representation으로부터 인스턴스를 생성하기 위한 메커니즘을 제공하는 프로토콜

해당 프로토콜을 이용하면 인스턴스를 자동으로 디코딩할 수 있다.

 

EX)  

- Decodable 사용 구조체

struct User: Decodable {
    var name: String
    var age: Int
}

 

 

- JSON 데이터

let json = """
{
    "name": "nelchupapa",
    "age": 26
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
let user = try decoder.decode(User.self, from: json)
print(user.name) // "nelchupapa"
print(user.age) // 26

 

여기서 JSON 키와 프로퍼티의 이름이 동일하지 않거나 지금처럼 간단한 예시가 아닌 복잡한 데이터 구조를 다룰 경우 init(from decoder: Decoder) 메서드를 사용해서 사용자 정의 디코딩을 구현하게도 할 수 있다.

 

 

https://developer.apple.com/documentation/swift/decodable

 

 

 

 

Encodable

Decodable과 반대로 JSON으로 변환하는 프로토콜이다. 말 그대로 데이터를 representation으로 인코딩할 수 있는 형식이다.

 

EX)

 

- 구조체

struct User: Encodable {
    var name: String
    var age: Int
}

 

 

- JSON 데이터

let user = User(name: "nelchupapa", age: 26)

let encoder = JSONEncoder()
let jsonData = try encoder.encode(user)
let jsonString = String(data: jsonData, encoding: .utf8)!
print(jsonString) // "{"name":"nelchupapa","age":26}"

 

encode(to encoder: Encoder) 메서드를 사용해서 사용자 정의 디코딩을 구현하게도 할 수 있다.

 

https://developer.apple.com/documentation/swift/encodable

 

 

 

 

Codable

 

Coadable은 위에서 언급한 두 가지 Decodable과 Encodable이 합쳐진 프로토콜.

 

 

 

 

CodingKey

swift에서는 기본적으로 변수와 상수에서 소문자 카멜 케이스를 사용하게 되는데, 이때 위에서 언급된 예시처럼 JSON 데이터의 경우도 동일 케이스로 작성되었다면 상관이 없지만 만약 케이스가 달라져 버린다면 이때 CodingKey를 사용한다.

 

 

JSON 데이터(User_Id 주목)

{
  "id": 1,
  "title": "정당의 목적이나 활동이 민주적 기본질서에 위배될 때에는 정부는 헌법재판소에 그 해산을 제소할 수 있고, 정당은 헌법재판소의 심판에 의하여 해산된다.",
  "content": "모든 국민은 인간으로서의 존엄과 가치를 가지며, 행복을 추구할 권리를 가진다. 모든 국민은 종교의 자유를 가진다. 국가는 농·어민과 중소기업의 자조조직을 육성하여야 하며, 그 자율적 활동과 발전을 보장한다. 모든 국민은 양심의 자유를 가진다. 누구든지 체포 또는 구속을 당한 때에는 즉시 변호인의 조력을 받을 권리를 가진다.",
  "createdAt": "2019-02-24T16:17:47.000Z",
  "updatedAt": "2019-02-24T16:17:47.000Z",
  "User_Id": 1
}

 

 

다른 키값들과 달리 가장 아래에 있는 User_Id의 경우 swift 환경에서는 스네이크 케이스를 적용할 수도 없게 되며, 서로 다른 키를 사용했으므로 오류를 만나는 것 당연한 일이다. 따라서 해당 경우 두 가지 해결책이 있는데 첫 번째는 JSON 키 값을 모두 swift에 맞게끔 변경하거나, CodingKey를 사용하면 됩니다. 당연히 99%의 사람들은 모두 후자를 선택하겠죠??

 

 

 

CodingKey 적용

enum CodingKeys: String, CodingKey {
        case id, title, content, createdAt, updatedAt
        case userID = "User_Id"
}

 

이제 우리는 JSON에 있는 User_Id 키 값을 swift환경에서는 userID라고 사용할 수 있게 된다.

 

 

 

 

 

 


참고

https://developer.apple.com/documentation/swift/codable

 

Codable | Apple Developer Documentation

A type that can convert itself into and out of an external representation.

developer.apple.com

https://developer.apple.com/documentation/swift/encodable

 

Encodable | Apple Developer Documentation

A type that can encode itself to an external representation.

developer.apple.com

https://developer.apple.com/documentation/swift/decodable

 

Decodable | Apple Developer Documentation

A type that can decode itself from an external representation.

developer.apple.com

https://developer.apple.com/documentation/swift/codingkey

 

CodingKey | Apple Developer Documentation

A type that can be used as a key for encoding and decoding.

developer.apple.com

 

반응형