JSONDecoder란?
JSONDecoder는 JSON 데이터를 Swift는 객체로 파싱하도록 도와주는 Decoder이다.
JSONDecoder 사용하기
JSONDecoder을 이용해 JSON을 Swift 객체로 파싱하기 위해서는 다음의 과정이 필요하다
- Decodable을 상속 받는 struct 생성하기
- Decodable에 저장된 데이터를 파싱하기
Decodable struct 만들기
Decodable 객체를 만들기 위해서는 JSON이 무엇인지 이해해야 한다. JSON이 무엇인지 모른다면 먼저 아래의 글을 통해 JSON이 무엇인지 알고보자.
[JSON] JSON은 무엇인가?
JSON이란 JSON(JavaScript Object Notation) 은 데이터를 키(key)-값(value) 쌍으로 만들어 저장하기 위한 포멧의 일종이다. { "id": 1, "priority": 999 } JSON은 위와 같은 포멧으로 저장되는데 ':'을 기준으로..
kotlinworld.com
JSON은 Key-Value, JsonObject, JsonArray 세가지로 구성된다. 이에 대한 struct를 만들기 위해서는 다음의 규칙을 지켜야 한다.
struct {struct 명칭}: Decodable {
let {Key}: {Value}
let {Key}: {JsonObject}
let {Key}: [{JsonArray 속의 JsonObject}]
}
예를 들어 다음의 JSON 데이터가 있다고 해보자.
{
"name": "DBlog",
"main": {
"today_visitors_num": 1200,
"total_visitors_num": 1000000
},
"posts": [
{
"id": 1,
"title": "JSON Data Converting",
"description": "Explains JSON Data Converting"
},
{
"id": 2,
"title": "JSON Data Get",
"description": "Explains JSON Data Get"
}
]
}
위 JSON은 다음의 규칙을 따른다.
- "name"이라는 {key}에 "DBlog"라는 String이 매핑된다.
- "main"이라는 {key}에 Main(todayVisitorsNum: Int,totalVisitorsNum: Int) struct가 매핑된다.
- "post"라는 {key}에 Array<Post(id: Int, title: String, description: String)이 매핑된다.
따라서 위 JSON을 struct로 변환시키면 다음과 같이 표현된다.
struct BlogInfo: Decodable {
let name: String
let main: Main
let posts: [Post]
}
struct Main: Decodable {
let todayVisitorsNum: Int
let totalVisitorsNum: Int
}
struct Post: Decodable {
let id: Int
let title: String
let content: String
}
위의 Decodable은 Codable로 대체해서 써도 무방하다. Codable은 Decodable과 Encodable을 포함하기 때문이다.
public typealias Codable = Decodable & Encodable
struct BlogInfo: Codable {
let name: String
let main: Main
let posts: [Post]
}
struct Main: Codable {
let todayVisitorsNum: Int
let totalVisitorsNum: Int
}
struct Post: Codable {
let id: Int
let title: String
let content: String
}
JSONDecoder이용해 파싱하기
위에서 만든 stuct를 이용해 JSON을 Swift의 struct로 파싱하는 과정은 간단하다. JSONDecoder의 decode 메서드를 사용하면 된다. 예를 들어 blogInfo가 JSON라고 할 때 다음과 같이 디코딩하여 decodedData의 생성이 가능하다.
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(BlogInfo.self, from: blogInfo)
//decodedData에 대한 처리
} catch {
print(error)
return nil
}
위의 코드에서 decodedData가 바로 BlogInfo struct가 되며 주석처리된 부분에서 decodedData에 대해 필요한 처리를 하면 된다.
'IOS > Swift' 카테고리의 다른 글
[Swift] Background Thread에서 Task 실행하기 (1) | 2021.12.26 |
---|---|
[Swift] internal parameter name과 external parameter name (0) | 2021.12.25 |
[Swift] 함수형 프로그래밍 알아보기 : 클로저(Closures), 일급객체 (0) | 2021.12.25 |
[Swift] protocol이란 무엇인가? (0) | 2021.12.22 |
[Swift] Struct와 Class의 차이는 무엇인가? (0) | 2021.12.20 |