원문 (블로그이전)
시리즈 | 🚀 iOS 네트워킹 정복하기 - averycode.log
요즘은 블로그대신 github 에 학습내용을 정리를 하게 되었는데,오랜만에 velog로 돌아와 iOS 네트워킹을 정복 시리즈를 작성해봅니다.iOS를 공부한지 몇개월이 지났는데 바쁘다는 핑계(?)로 네트워
velog.io
Codable
typealias Codable = Decodable & Encodable
- 자신을 "외부표현"으로 변환하거나 변활할 수 있는 타입
- Codable 은 Encodable 과 Decodable protocol로 구성된 유니온 타입(union type)으로 정의할 수 있다.
- "외부표현" : 보통 JSON이나, property-list...
- 프로토콜로 Class, Enum, Struct 모두에서 채택가능
Codable 을 채택했다 = Class, Struct, Enum을 serialize / deserialize할 수 있다
Decodable, Encodable
Codable : Decodable 과 Encodable 을 모두 채택합니다.
이때, Decodable과 Encodable 은 다음과 같습니다.
- Decodable : 자신을 외부표현으로 디코딩 할 수 있는 타입 (ex - JSON -> 자신)
- Encodable : 자신을 외부표현으로 인코딩 할 수 있는 타입 (ex - 자신 -> JSON)
Encoding
PropertyListEncoder 나 JSONEncoder 클래스로 인코딩을 할 수 있습니다.
.encode
메소드는 Encodable 타입을 준수하는 T 를 JSON Data 로 리턴해준다
🚗 예시를 보자!
1. Codable 프로토콜을 채택한 Car 구조체가 있다
struct Car: Codable {
let name: String
let brand: String
let age: Int
}
2. Car 구조체를 JSON 으로 인코딩해보자
let data = Car(name: "taycan", brand: "porsche", age: 2)
let encoder = JSONEncoder() // 1️⃣ JSON Encoder 선언
let jsonData = try? encoder.encode(data) // 2️⃣ Data 타입으로 변환
if let jsonData = jsonData, let jsonString = String(data: jsonData, encoding: .utf8) {
print("🚗")
print(jsonString)
print("🚗")
} // 3️⃣ Data 타입을 String 으로 만듬
// ✅ if let 인 이유
// 1. try? -> jsonData 가 optional 이다.
// 2. 2. String(data: , encoding: )의 리턴타입 -> String? => optional
출력결과는 아래와 같다
🚗
{"name":"taycan","brand":"porsche","age":2}
🚗
근데 json 은 약간 그 모양
이 국룰인데....?그 모양
을 아래에서 만들어보자
3. encoder의 출력결과를 이쁘게 만들어보자 🌈 (JSONEncoder.OutputFormatting)
JSONEncoder.OutputFormatting 을 사용하면 된다!
encoder.outputFormatting = .prettyPrinted // json 모양으로 이쁘게 출력
encoder.outputFormatting = .sortedKeys // key 를 abcd 순으로 출력
encoder.outputFormatting = .withoutEscapingSlashes // *escaping slash를 제거
escaping slash를 제거
url값을 "https://google.com" 으로 보냈는데, 실제 json 파일에서 "https://google.com"로 되는 것을 방지할 수 있음
여러개를 한번에 적용하면
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
짠!
Decoding
이번엔 반대로 Decoding 을 해봅시다
1. Codable 프로토콜을 채택한 Car 구조체가 있다
struct Car: Codable {
let name: String
let brand: String
let age: Int
}
2. Car 구조체를 JSON 으로 디코딩해보자
// 1️⃣ JSONDecoder 선언
let decoder = JSONDecoder()
// 2️⃣ 임시로 JSON Data를 만들어봅시다 (위에서 내용 사용)
let data = jsonString.data(using: .utf8)
// 3️⃣ .decode 메소드로 data -> 인스턴스
if let data = data, let myCar = try? decoder.decode(Car.self, from: data) {
print("🚀🚀🚀🚀")
print(myCar.name)
print(myCar.brand)
print(myCar.age)
print("🚀🚀🚀🚀")
}
출력결과
🚀🚀🚀🚀
taycan
porsche
2
🚀🚀🚀🚀
JSONDecoder 의 .decode
메소드를 봅시다
- type : Decodable 을 준수해야함 / JSON으로 만들고 싶은 데이터 타입을 정의 (타입.self)
- data : Decoding 하려는 데이터
Nullable & Optional Key
특정필드의 값이 nullable 하거나 optional 한 key의 경우 struct을 아래와 같이 정의할 수 있다!
struct Car: Codable {
let name: String
let brand: String
let age: Int?
}
기본값 할당은 아래처럼
struct Car: Codable {
let name: String
let brand: String
let age: Int = 0
}
References
https://zeddios.tistory.com/373
https://inuplace.tistory.com/895?category=1034357
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
https://medium.com/doyeona/codable-decodable-encodable-feat-json-5643dc3d7766
http://minsone.github.io/programming/swift-codable-and-exceptions-extension
https://kyungmosung.github.io/2020/08/17/swift-codable-enum/
https://developer.apple.com/documentation/swift/codable
https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
'이전 블로그 > iOS Dev' 카테고리의 다른 글
🚀 iOS 네트워킹 정복하기 (5) ATS (App Transport Security) (0) | 2022.11.02 |
---|---|
🚀 iOS 네트워킹 정복하기 (4) CodingKeys / Custom 인코딩과 디코딩 (0) | 2022.11.02 |
🚀 iOS 네트워킹 정복하기 (2) URLSession (1) | 2022.11.02 |
🚀 iOS 네트워킹 정복하기 (1) Kick Off (0) | 2022.11.02 |
[Swift] Struct와 Class (feat. 값타입과 참조타입) (0) | 2022.11.02 |