ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [ios - Swift] Codable을 사용한 Json 데이터 가져오기
    ios 2020. 11. 13. 20:00

     

     

     

     

    1. 준비 단계

    우선 지난 시간에 학습해 본 Json 데이터를 가져올 API URL이 필요합니다.

    기존 시간에 배운 내용에서 수정을 할 것이므로 Json 파싱 방법을 모를 경우 아래 링크에서 확인해 주세요.

     

     

    poky-develop.tistory.com/4

     

     

     

    2. Codable

    Codable 이란 Swift4에서 추가되었으며 Json 처리를 쉽게 도와줍니다.

     

    Json의 키가 변수명과 일치하게 사용하면 됩니다.

     

    다만 변수명을 다르게 설정하고 싶다면 CodingKeys 적용이 필요합니다.

     

     

     

    3. Model Class 만들기

     

    우선 codable을 상속받은 class를 생성합니다.

     

    class 내 변수 명은 Json의 Key와 동일하게 작성합니다.

     

    //
    //  Exchange.swift
    //  RefreshControlSample
    //
    //  Created by 조용호 on 2020/11/12.
    //
    
    import Foundation
    
    public class Exchange : Codable {
        public var symbol : String?
        public var name : String?
        public var price : String?
        public var date : String?
        public var timestamp : String?
        public var kr : String?
        public var en : String?
        public var jp : String?
    
    }
    

     

     

     

     

     

    이제 지난번에 작성한 소스를 수정하고 클래스 객체에 넣도록 합니다.

     

    수정 전

    func GetURLSessionData() {
        let newsAddress : String = "https://api.manana.kr/exchange.json"
    
        let task = URLSession.shared.dataTask(with: URL(string: newsAddress)!) { (data, response, error) in
    
        if let pData = data {
          do {
              let json = try JSONSerialization.jsonObject(with: pData, options:[]) as! Array<Dictionary<String, Any>>
    
              for (idx, value) in json.enumerated() {
                if let symbol = value["symbol"] {
                	print("\(idx) - \(symbol)")
              	}	
              }
            } catch {
    
            }
          }
    	}
        task.resume()
    }
        

     

    수정 후

     

    func GetURLSessionData() {
        let newsAddress : String = "https://api.manana.kr/exchange.json"
    
        let task = URLSession.shared.dataTask(with: URL(string: newsAddress)!) { (data, response, error) in
    
            if let pData = data {
                do {
    
                    if let myList = try? JSONDecoder().decode(Array<Exchange>.self, from: pData) {
    					print("\(exchange.symbol)")
                    }
    
                } catch {
                    print(error)
                }
            }
        }
        task.resume()
    }

     

    수정된 결과를 보면 클래스 리스트에 잘 들어간 것을 확인할 수 있습니다. 

     

    댓글

Designed by Tistory.