JSONDecoder로 디코딩하기
JSON 데이터를 형식이 지정된 Swift 값으로 구문 분석합니다.
JSONDecoder로 디코딩하기은(는) CoddyKit의 무료 Swift Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Swift Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Swift Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
JSONDecoder 생성
JSONDecoder는 JSON Data에서 Swift 값을 다시 구성합니다. 만들고 싶은 타입을 지정하고 바이트를 전달하면 됩니다.
import Foundation
struct City: Codable {
var name: String
var population: Int
}
let json = "{\"name\":\"Oslo\",\"population\":700000}"
let data = json.data(using: .utf8)!
let city = try JSONDecoder().decode(City.self, from: data)
print(city.name, city.population).self로 타입 전달하기
첫 번째 인수는 메타타입이며 MyType.self로 작성합니다. 이렇게 하면 디코더가 데이터에서 어떤 구조를 만들어야 하는지 알 수 있습니다.
import Foundation
struct Flag: Codable { var ok: Bool }
let data = "{\"ok\":true}".data(using: .utf8)!
let result = try JSONDecoder().decode(Flag.self, from: data)
print(result.ok)배열 디코딩
JSON 배열을 디코딩하려면 [Int].self 또는 [MyStruct].self와 같은 배열 타입을 요청합니다.
import Foundation
let json = "[10, 20, 30]"
let data = json.data(using: .utf8)!
let numbers = try JSONDecoder().decode([Int].self, from: data)
print(numbers.reduce(0, +))중첩 객체 디코딩
중첩된 JSON 객체는 중첩된 Codable 구조체에 대응합니다. 디코더가 트리를 따라가며 각 단계의 값을 대신 채웁니다.
import Foundation
struct Coord: Codable { var lat: Double; var lon: Double }
struct Place: Codable { var name: String; var coord: Coord }
let json = "{\"name\":\"X\",\"coord\":{\"lat\":1.0,\"lon\":2.0}}"
let p = try JSONDecoder().decode(Place.self, from: json.data(using: .utf8)!)
print(p.coord.lat, p.coord.lon)디코딩 오류 처리
데이터가 타입과 일치하지 않으면 decode가 오류를 발생시킵니다. do/catch로 감싸 잘못된 입력을 적절하게 처리하세요.
import Foundation
struct User: Codable { var name: String }
let bad = "{\"wrong\":1}".data(using: .utf8)!
do {
let u = try JSONDecoder().decode(User.self, from: bad)
print(u.name)
} catch {
print("Failed:", error)
}keyNotFound 오류
필수 키가 누락되었을 때 발생하는 일반적인 오류가 DecodingError.keyNotFound입니다. 오류를 패턴 매칭하면 정확히 무엇이 잘못되었는지 알릴 수 있습니다.
import Foundation
struct User: Codable { var name: String }
let bad = "{}".data(using: .utf8)!
do {
_ = try JSONDecoder().decode(User.self, from: bad)
} catch let DecodingError.keyNotFound(key, _) {
print("Missing key:", key.stringValue)
} catch {
print("Other error:", error)
}typeMismatch 오류
값의 JSON 타입이 잘못된 경우, 예를 들어 Int가 필요한 곳에 문자열이 있으면 디코더가 DecodingError.typeMismatch를 발생시킵니다.
import Foundation
struct Count: Codable { var n: Int }
let bad = "{\"n\":\"oops\"}".data(using: .utf8)!
do {
_ = try JSONDecoder().decode(Count.self, from: bad)
} catch let DecodingError.typeMismatch(type, _) {
print("Type mismatch, expected:", type)
} catch {
print("Other:", error)
}dataCorrupted 오류
JSON 문법이 유효하지 않으면 DecodingError.dataCorrupted가 발생합니다. 일반적으로 바이트가 아예 올바른 JSON이 아니라는 뜻입니다.
import Foundation
struct User: Codable { var name: String }
let bad = "not json".data(using: .utf8)!
do {
_ = try JSONDecoder().decode(User.self, from: bad)
} catch is DecodingError {
print("Decoding failed: data corrupted")
} catch {
print("Other:", error)
}옵셔널로 디코딩하기
프로퍼티가 옵셔널이면 키가 없어도 오류가 발생하지 않고 nil로 디코딩됩니다. 따라서 옵셔널 필드는 데이터가 누락되어도 유연하게 처리할 수 있습니다.
import Foundation
struct Profile: Codable {
var name: String
var bio: String?
}
let json = "{\"name\":\"Kai\"}"
let p = try JSONDecoder().decode(Profile.self, from: json.data(using: .utf8)!)
print(p.name, p.bio ?? "no bio")디코더 재사용
인코더와 마찬가지로 설정한 JSONDecoder를 여러 페이로드에 재사용할 수 있습니다. 하나의 인스턴스를 유지하고 서로 다른 입력을 디코딩하세요.
import Foundation
struct Word: Codable { var text: String }
let decoder = JSONDecoder()
let inputs = ["{\"text\":\"hi\"}", "{\"text\":\"bye\"}"]
for s in inputs {
let w = try decoder.decode(Word.self, from: s.data(using: .utf8)!)
print(w.text)
}디코딩, 확인, 사용
전체 흐름은 Data를 받고, do/catch 안에서 타입이 지정된 값으로 디코딩한 다음, 타입이 명확한 결과를 안전하게 사용하는 것입니다.
import Foundation
struct Weather: Codable {
var city: String
var temp: Double
}
let json = "{\"city\":\"Rome\",\"temp\":21.5}"
do {
let w = try JSONDecoder().decode(Weather.self, from: json.data(using: .utf8)!)
print("\(w.city): \(w.temp)C")
} catch {
print("Decode error:", error)
}빠른 확인: JSONDecoder
디코딩에 대한 지식을 테스트해 보세요.
복습: JSONDecoder로 디코딩하기
JSON에서 Swift 값을 다시 구성하는 방법을 배웠습니다:
decode(MyType.self, from: data)는 타입이 지정된 값을 만듭니다.- 배열, 중첩 객체, 옵셔널은 자동으로 디코딩됩니다.
decode는DecodingError의 다음 경우를 발생시킵니다:keyNotFound,typeMismatch,dataCorrupted,valueNotFound.- 잘못된 입력을 처리하려면 호출을
do/catch로 감싸세요.
자주 묻는 질문
“JSONDecoder로 디코딩하기” 강의는 무료인가요?
네 — “JSONDecoder로 디코딩하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Swift Academy 강의 전체를 잠금 해제할 수 있습니다. Swift Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“JSONDecoder로 디코딩하기”에서 뭘 배우나요?
JSON 데이터를 형식이 지정된 Swift 값으로 구문 분석합니다. 브라우저에서 직접 실행하는 실습 코드로 Swift Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Swift Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Swift Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“JSONDecoder로 디코딩하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Swift Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Swift Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Codable 따르기
- JSONEncoder로 인코딩하기
- JSONDecoder로 디코딩하기
- 옵셔널과 중첩 형식 처리