투케이2K

94. (TWOK/ALGORITHM) [Swift] 문법 - Codable (코더블) 사용해 VO 클래스 객체 매핑 및 JSON 생성 , 파싱 본문

투케이2K 알고리즘

94. (TWOK/ALGORITHM) [Swift] 문법 - Codable (코더블) 사용해 VO 클래스 객체 매핑 및 JSON 생성 , 파싱

투케이2K 2023. 1. 24. 11:14
반응형

[환경 설정 및 설명]

언어 : Swift

설 명 : 문법 - Codable (코더블) 사용해 VO 클래스 객체 매핑 및 JSON 생성 , 파싱

 

[실행 : 소스 코드]

    func testMain(){
        print("")
        print("===============================")
        print("[ViewController >> testMain() :: 테스트 함수 수행 실시]")
        print("===============================")
        print("")
        
        
        // MARK: [JSON 인코딩 수행 실시]
        var jsonEncode = ""
        do {
            // [배열 데이터를 만들기 위한 데이터 삽입]
            let encode_color = ["red", "yellow"]
            
            
            // [다중 json 형태를 만들기 위한 common 데이터 삽입]
            let encode_phone : jsonCommonOs = jsonCommonOs(os: "android", version: "12.1")
            
            
            // [Array Json 형태를 만들기 위한 common 데이터 삽입]
            let encode_job : [jsonCommonJob] = [jsonCommonJob(job: "dev", year: 2019), jsonCommonJob(job: "dev", year: 2020)]

            
            // [구조체 데이터 정의]
            let encodeData = jsonEncodeStruct(name: "투케이", age: 28, color: encode_color, phone: encode_phone, job: encode_job)
            
            
            // [json 데이터 생성]
            let jsonCreate = try JSONEncoder().encode(encodeData)
            
            
            // [json 데이터를 변수에 삽입 실시]
            jsonEncode = String(data: jsonCreate, encoding: .utf8) ?? ""
            print("")
            print("===============================")
            print("[json 인코딩 :: \(jsonEncode)]")
            print("===============================")
            print("")
        } catch {
            print("")
            print("===============================")
            print("[error [에러] :: \(error.localizedDescription)]")
            print("===============================")
            print("")
        }
        
        
        
        
        
        // MARK: [JSON 디코딩 수행 실시]
        do {
            // [String 형식 json을 Data 타입으로 변환 수행 실시]
            let decodeData = jsonEncode.data(using: .utf8)
            
            
            // [구조체 사용해 json 개별 데이터 확인 실시]
            let decodeJson = try JSONDecoder().decode(jsonDecodeStruct.self, from: decodeData!)
            print("")
            print("===============================")
            print("[json 디코딩 [전체] :: \(decodeJson)]")
            print("-------------------------------")
            print("[json 디코딩 [name] :: \(decodeJson.name)]")
            print("[json 디코딩 [age] :: \(decodeJson.age)]")
            print("-------------------------------")
            print("[json 디코딩 [color [0]] :: \(decodeJson.color[0])]")
            print("[json 디코딩 [color [1]] :: \(decodeJson.color[1])]")
            print("-------------------------------")
            print("[json 디코딩 [os] :: \(decodeJson.phone.os)]")
            print("[json 디코딩 [version] :: \(decodeJson.phone.version)]")
            print("===============================")
            print("")
            
            
            // [for 문을 사용해서 Array Json 형태 데이터 파싱 수행]
            for i in stride(from: 0, through: 1, by: 1){
                print("")
                print("===============================")
                print("[json 디코딩 [job] :: \(decodeJson.job[i].job)]")
                print("[json 디코딩 [year] :: \(decodeJson.job[i].year)]")
                print("===============================")
                print("")
            }
        } catch {
            print("")
            print("===============================")
            print("[error [에러] :: \(error.localizedDescription)]")
            print("===============================")
            print("")
        }
    }
 

[VO 모델 클래스 : 소스 코드]

import Foundation


// MARK: - [클래스 설명]
/*
// -----------------------------------------
1. Codable 사용해 json 인코딩 , 디코딩 수행 클래스
// -----------------------------------------
*/





// MARK: - [Codable 설명]
/*
// -----------------------------------------
1. Codable : Swift4 부터 추가된 프로토콜이며, JSON 데이터를 간편하게 인코딩 , 디코딩을 수행할 수 있습니다
2. Codable 은 struct, enum, class 에서 전부 사용할 수 있습니다
3. 일반적으로 struct 를 사용해 JSON 데이터를 인코딩 , 디코딩을 수행합니다
// -----------------------------------------
*/





// MARK: - [JSON [공통] 구조 : 이중 JSON 만들기]
struct jsonCommonOs : Codable {
    var os : String
    var version : String
}





// MARK: - [JSON [공통] 구조 : Array Json 만들기]
struct jsonCommonJob : Codable {
    var job : String
    var year : Int
}





// MARK: - [JSON 인코딩 수행 실시]
struct jsonEncodeStruct : Codable {
    
    var name : String // [일반 key , value]
    var age : Int // [일반 key , value]
    var color : Array<String> // [배열 데이터]
    var phone : jsonCommonOs // [이중 JSON 형식]
    var job : [jsonCommonJob] // [Array Json 형식]
    
    
    // [구조체 생성자 초기화 실시]
    init(name: String, age: Int, color: Array<String>, phone:jsonCommonOs, job:[jsonCommonJob]){
        // [전역 변수 = 인풋 값]
        self.name = name // [일반 key , value]
        self.age = age // [일반 key , value]
        self.color = color // [배열 데이터]
        self.phone = phone // [이중 JSON 형식]
        self.job = job // [Array Json 형식]
    }
}





// MARK: - [JSON 디코딩 수행 실시]
struct jsonDecodeStruct : Codable {
    
    var name : String // [일반 key , value]
    var age : Int // [일반 key , value]
    var color : Array<String> // [배열 데이터]
    var phone : jsonCommonOs // [이중 JSON 형식]
    var job : [jsonCommonJob] // [Array Json 형식]
    
    
    // [구조체 생성자 초기화 실시]
    init(name: String, age: Int, color: Array<String>, phone: jsonCommonOs, job:[jsonCommonJob]){
        // [전역 변수 = 인풋 값]
        self.name = name // [일반 key , value]
        self.age = age // [일반 key , value]
        self.color = color // [배열 데이터]
        self.phone = phone // [이중 JSON 형식]
        self.job = job // [Array Json 형식]
    }
}
 

[결과 출력]


반응형
Comments