본문 바로가기
#모바일 [Mobile]/iOS

[iOS] JSONEncoder / JSONDecoder

by cy_mos 2019. 5. 1.
반응형

 


  • 스위프트 4 버전 이전에는 JSONSerialization을 사용해 JSON 타입의 데이터를 생성했습니다. 그러나 스위프트 4 버전부터 JSONEncoder / JSONDecoder가 Codable 프로토콜을 지원하기 때문에 JSONEncoder / JSONDecode와 Codable 프로토콜을 이용해 손쉽게 JSON 형식으로 인코딩 및 디코딩할 수 있습니다. 즉, JSONEncoder 및 JSONDecoder를 활용하여 스위프트 타입의 인스턴스를 JSON 데이터로 인코딩, JSON 데이터에서 스위프트 타입의 인스턴스로 디코딩할 수 있습니다.

📚 JSON (JavaScript Object Notation) 이란?

Using JSON with Custom Types - Apple Documentation

JSON (제이슨[1], JavaScript Object Notation)은 속성-값 쌍( attribute–value pairs and array data types (or any other serializable value)) 또는 "키-값 쌍"으로 이루어진 데이터 오브젝트를 전달하기 위해 인간이 읽을 수 있는 텍스트를 사용하는 개방형 표준 포맷이다. 비동기 브라우저/서버 통신 (AJAX)을 위해, 넓게는 XML(AJAX가 사용)을 대체하는 주요 데이터 포맷이다. 특히, 인터넷에서 자료를 주고 받을 때 그 자료를 표현하는 방법으로 알려져 있다. 자료의 종류에 큰 제한은 없으며, 특히 컴퓨터 프로그램의 변수값을 표현하는 데 적합하다.


📄 JSONEncoder

  • An object that encodes instances of a data type as JSON objects.
truct GroceryProduct: Codable {
    var name: String
    var points: Int
    var description: String?
}

let pear = GroceryProduct(name: "Pear", points: 250, description: "A ripe pear.")

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted

let data = try encoder.encode(pear)
print(String(data: data, encoding: .utf8)!)

/* Prints:
 {
   "name" : "Pear",
   "points" : 250,
   "description" : "A ripe pear."
 }
*/

📄 JSONDecoder

  • An object that decodes instances of a data type from JSON objects.
struct GroceryProduct: Codable {
    var name: String
    var points: Int
    var description: String?
}

let json = """
{
    "name": "Durian",
    "points": 600,
    "description": "A fruit with a distinctive scent."
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
let product = try decoder.decode(GroceryProduct.self, from: json)

print(product.name) // Prints "Durian"

🚀 REFERENCE

 

[부스트코스] iOS 프로그래밍 강좌소개 : edwith

- 부스트코스

www.edwith.org

 

Using JSON with Custom Types | Apple Developer Documentation

Sample Code Using JSON with Custom Types Demonstrates approaches for encoding and decoding different kinds of JSON in Swift. Download OverviewJSON data you send or receive from other apps, services, and files can come in many different shapes and structure

developer.apple.com

 

반응형

댓글