[iOS] JSONSerialization vs JSONEncoder 차이 정리

황석범·2025년 2월 10일
0

내일배움캠프_iOS_5기

목록 보기
75/76

JSONSerialization vs JSONEncoder

Swift에서 JSON 데이터를 생성하는 방법으로 JSONSerialization과 JSONEncoder의 차이에 대해 정리해보자


1. JSONSerializtion.data(withJSONObject:options:)dd

특징

  • Foundation 객체(Dictionary<String, Any> 또는 Array)를 JSON으로 변환
  • 타입 안정성이 부족 (Any 타입 사용)
  • Codable을 사용하지 않음
  • 수동 변환이 필요할 수도 있음
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}
}

단점

  • Any 타입 사용으로 인한 런타임 오류 가능성
  • Swift 데이터 모델(struct, class)을 활용할 수 없음
  • Date 변환 등 추가 작업 필요

2. JSONEncoder

특징

  • Codable 프로토콜을 준수하는 struct 또는 class를 JSON으로 변환
  • 타입 안정성이 뛰어남
  • Date 포맷, snake_case 변환 등 옵션 설정 가능
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}
} 

장점

  • Codable을 활용하여 타입 안정성 유지
  • 유지보수와 확장성이 뛰어남
  • outputFormatting 옵션을 통해 가독성 좋은 JSON 출력 가능
 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)
}

3. 차이점 비교

비교 항목JSONSerializationJSONEncoder
타입 안정성Any 타입 사용 (런타임 오류 가능)Codable을 통해 타입 안정성 보장
사용 방식Dictionary 또는 Array 사용Codable을 준수하는 struct/class 사용
코드의 직관성직접 변환해야 함간결하고 직관적인 코드
유연성Foundation 객체(NSDictionary, NSArray) 변환 가능Swift 데이터 모델을 활용 가능
성능빠르지만 런타임 오류 가능성더 안전하고 유지보수하기 쉬움
메시지 필터링직접 구현해야 함API 내장
구조체(Struct), 열거형(Enum) 지원지원 안됨 (클래스만 가능)가능
프로토콜 채택 가능가능가능

profile
iOS 공부중...

0개의 댓글

관련 채용 정보