JSON, Codable

Groot·2022년 6월 27일
0

TIL

목록 보기
24/148
post-thumbnail

TIL

🌱 난 오늘 무엇을 공부했을까?

📌 JSON이란?

  • JSON(JavaScript Object Notation)은 속성-값 쌍(attribute–value pairs), 배열 자료형(array data types) 또는 기타 모든 시리얼화 가능한 값(serializable value) 또는 "키-값 쌍"으로 이루어진 데이터 오브젝트를 전달하기 위해 인간이 읽을 수 있는 텍스트를 사용하는 개방형 표준 포맷이다.

📍 JSON의 기본 자료형

  • 수(Number)
  • 문자열(String): 0개 이상의 유니코드 문자들의 연속. 문자열은 큰 따옴표(")로 구분하며 역슬래시 이스케이프 문법을 지원한다.
  • 참/거짓(Boolean): true 또는 false 값
  • 배열(Array): 0 이상의 임의의 종류의 값으로 이루어진 순서가 있는 리스트. 대괄호로 나타내며 요소는 쉼표로 구분한다.
  • 객체(Object): 순서가 없는 이름/값 쌍의 집합으로, 이름(키)이 문자열이다.
  • null: 빈 값으로, null을 사용한다.

📍 JSON의 장점

  • JSON은 텍스트로 이루어져 있으므로, 사람과 기계 모두 읽고 쓰기 쉽다.
  • 프로그래밍 언어와 플랫폼에 독립적이므로, 서로 다른 시스템간에 객체를 교환하기에 좋다.
    참고

📌 Codable

  • 디코딩 또는 인코딩을 위한 Type Alias
  • 스위프트에서의 정의
    typealias Codable = Decodable & Encodable
  • 디코딩 시 Decodable 채택, 인코딩 시 Encodable을 채택해서 각각 변환가능
  • Codable을 유형 또는 일반 제약 조건으로 사용하면 두 프로토콜을 모두 준수

📍 알고가야 할 목록

  • protocol Encodable
    • 인코딩을 위한 타입.
  • protocol Decodable
    • 디코딩을 위한 타입.
  • protocol CodingKey
    • 인코딩 및 디코딩을 위한 키로 사용할 수 있는 형식(Int, String).
    • 주로 snake case('_')을 camel case로 바꿀 때 사용(keyDecodingStrategy을 이용하는 방법도 있음! )
  • protocol CodingKeyRepresentable
    • 코딩 키로 변환할 수 있는 유형.
  • struct CodingUserInfoKey
    • 인코딩 및 디코딩 중에 컨텍스트를 제공하기 위한 사용자 정의 키.

📌 JsonDecoder

  • JSON 개체에서 데이터 유형의 인스턴스를 디코딩하는 개체
  • JSONDecoder 인스턴스를 사용하여 디코딩할 수 있도록 Codable을 채택.

📍 공식문서 예제 해석해보기

struct GroceryProduct: Codable {
    var name: String // json 데이터 형식의 name 키
    var points: Int // json 데이터 형식의 points 키
    var description: String? // json 데이터 형식의 description 키
}

let json = """
{
    "name": "Durian",
    "points": 600,
    "description": "A fruit with a distinctive scent."
}
""".data(using: .utf8)! // Swift 문자열을 UTF-8 데이터로 변환, Data(string.utf8)와 같이 안전한 방법으로 변환 가능

let decoder = JSONDecoder() // JSONDecoder 인스턴스 생성
let product = try decoder.decode(GroceryProduct.self, from: json)
// JSON 개체에서 지정한 유형의 디코딩된 값을 반환.
// json을 GroceryProduct유형으로 디코딩 후 GroceryProduct 유형으로 반환
print(product.name) // Prints "Durian", name 키로 접근

🔗 Array 형식의 JSON 디코딩

    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."
        },
        {
            "name": "Apple",
            "points": 200,
            "description": "A fruit with a distinctive scent."
        }
    ]
    """.data(using: .utf8)!

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

    print(product[0].name) // Prints "Durian"
    print(product[1].name) // Prints "Apple"

Codable
JSONDecoder

profile
I Am Groot

0개의 댓글