Olive Study Room
[Swift] Json 다루기 본문
Codable
typealias Codable = Decodable & Encodable
스위프트의 인스턴스를 다른 데이터 형태로 변환하고 그 반대의 역할을 수행하는 방법을 제공
스위프트의 인스턴스를 다른 데이터 형태로 변환할 수 있는 기능을 Encodable 프로토콜로, 그 반대의 역할을 할 수 있는 기능을 Decodable로 표현. 그 둘을 합한 타입을 Codable로 정의
Decodable
스위프트 타입의 인스턴스로 디코딩할 수 있는 프로토콜
Encodable :
스위프트 타입의 인스턴스를 인코딩할 수 있는 프로토콜
* 인코딩 : 정보의 형태나 형식을 표준화, 보안, 처리 속도 향상, 저장 공간 절약 등을 위해서 다른 형태나 형식으로 변환하는 처리 혹은 그 처리 방식(출처 : 위키백과 - 부호화).
* 디코딩 : 인코딩의 반대 작업을 수행하는 것
JSONEncoder
Codable 프로토콜을 준수하는 인스턴스를 JSON 데이터로 인코딩하는 방법
import UIKit
// codable 프로토콜을 준수하는 구조체 생성
struct GroceryProduct: Codable{
var name: String
var points: Int
var description: String
}
// Encoding
// 객체 생성
let pear = GroceryProduct(name: "Pear", points: 250, description: "A ripe pear")
// 인코더 객체와 아웃풋 포맷 설정
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
// 데이터 인코딩, 출력
do{
let data = try encoder.encode(pear)
print(String(data: data, encoding: .utf8)!)
}catch{
print(error)
}
JSONEncoder
JSON 데이터를 Codable 프로토콜을 준수하는 인스턴스로 디코딩하는 방법
// decoding
let json = """
{
"name": "Durian",
"points": 600,
"description": "A fruit with a distinctive scent."
}
""".data(using: .utf8)!
let decoder = JSONDecoder()
do {
// 해당 구조체와 이름(파일 이름)으로 디코딩해서 불러옴.
let product = try decoder.decode(GroceryProduct.self, from: json)
print(product.name)
} catch {
print(error)
}
자료 출처 : www.boostcourse.org/mo326
'Coding > iOS' 카테고리의 다른 글
[iOS] Photos Framework (1) 개념 (0) | 2021.04.13 |
---|---|
[Swift] GCD? (Dispatch Queue & OperationQueue) (1) | 2021.04.06 |
[iOS] UITableView의 생성, cell 삭제 (0) | 2021.03.10 |
1일차 - 로드맵의 이해 (0) | 2021.01.02 |
공부 시작 (0) | 2021.01.02 |
Comments