Swift에서 JSON 데이터를 생성하는 방법으로 JSONSerialization과 JSONEncoder의 차이에 대해 정리해보자
let requestPayload: [String: Any] = [
"name": "Alice",
"age": 25,
"isStudent": false
]
if let jsonData = try? JSONSerialization.data(withJSONObject: requestPayload, options: []) {
print(String(data: jsonData, encoding: .utf8)!) // {"name":"Alice","age":25,"isStudent":false}
}
struct User: Codable {
let name: String
let age: Int
let isStudent: Bool
}
let user = User(name: "Alice", age: 25, isStudent: false)
if let jsonData = try? JSONEncoder().encode(user) {
print(String(data: jsonData, encoding: .utf8)!) // {"name":"Alice","age":25,"isStudent":false}
}
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
JSONSerializtion도 가독성 좋은 JSON을 출력할 수 있다.
if let jsonData = try? JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted),
let jsonString = String(data: jsonData, encoding: .utf8) {
print(jsonString)
}
비교 항목 | JSONSerialization | JSONEncoder |
---|---|---|
타입 안정성 | Any 타입 사용 (런타임 오류 가능) | Codable을 통해 타입 안정성 보장 |
사용 방식 | Dictionary 또는 Array 사용 | Codable을 준수하는 struct/class 사용 |
코드의 직관성 | 직접 변환해야 함 | 간결하고 직관적인 코드 |
유연성 | Foundation 객체(NSDictionary, NSArray) 변환 가능 | Swift 데이터 모델을 활용 가능 |
성능 | 빠르지만 런타임 오류 가능성 | 더 안전하고 유지보수하기 쉬움 |
메시지 필터링 | 직접 구현해야 함 | API 내장 |
구조체(Struct), 열거형(Enum) 지원 | 지원 안됨 (클래스만 가능) | 가능 |
프로토콜 채택 가능 | 가능 | 가능 |