100 days of Swift - Day 33(Codable)

sun02·2021년 9월 23일
0

100 days of Swift 

목록 보기
27/40

JSON = JavaScript Object Notation


{
    "metadata":{
        "responseInfo":{
            "status":200,
            "developerMessage":"OK",
        }
    },
    "results":[
        {
            "title":"Legal immigrants should get freedom before undocumented immigrants – moral, just and fair",
            "body":"I am petitioning President Trump's Administration to take a humane view of the plight of legal immigrants. Specifically, legal immigrants in Employment Based (EB) category. I believe, such immigrants were short changed in the recently announced reforms via Executive Action (EA), which was otherwise long due and a welcome announcement.",
            "issues":[
                {
                    "id":"28",
                    "name":"Human Rights"
                },
                {
                    "id":"29",
                    "name":"Immigration"
                }
            ],
            "signatureThreshold":100000,
            "signatureCount":267,
            "signaturesNeeded":99733,
        },
        {
            "title":"National database for police shootings.",
            "body":"There is no reliable national data on how many people are shot by police officers each year. In signing this petition, I am urging the President to bring an end to this absence of visibility by creating a federally controlled, publicly accessible database of officer-involved shootings.",
            "issues":[
                {
                    "id":"28",
                    "name":"Human Rights"
                }
            ],
            "signatureThreshold":100000,
            "signatureCount":17453,
            "signaturesNeeded":82547,
        }
    ]
}

-> 받으려는 JSON 데이터의 일부

  • metadata는 responseInfo를 포함하고 있는데 이것은 상태 값을 가진다. status 200은 개발자들이 "모든 것이 OK이다"라고 말하기 위해 사용한다.

  • results는 청원들을 포함한다.

    • 각각의 청원에는 title, body, issues, signature 정보가 포함되어있다.

Swift 에는 JSON 작업을 지원하는 내장 프로토콜인 Codable이 있다.

String, Int 와 같은 기본 유형들은 자동으로 Codable을 따르고 배열과 딕셔너리들도 Codable객체를 포함하는 경우 Codable을 따른다.

  • 즉 String이 Codable을 따르기 때문에 [String]도 Codable을 따른다

struct Petition {
	var title: String
    var body: String
    var signatureCount: Int
}
  • 새로운 Swift 파일 생성하여 다음과 같이 작성한다.
  • 하나의 청원을 저장하는 Petition이라는 사용자 지정 구조체이다.
    • 제목 string, 본문 string, 서명 Int를 추적한다.

struct Petition: Codable {
	var title: String
    var body: String
    var signatureCount: Int
}
  • Petition 구조체에는 두 개의 문자열과 정수가 포함되어 있고 이들은 이미 Codable을 준수하기 때문에 Swift에 Petition 타입이 Codable을 준수하도록 요청할 수 있다.

struct Petitions: Codable {
	var results: [Petition]
}
  • JSON파일을 통해 청원들이 results라는 딕셔너리 안에 들어있음을 확인할 수 있다.
    • Swift가 JSON을 분석할 때 먼저 results를 로드한 다음 그 안의 청원 결과 배열을 로드해야한다.

var petitions = [Petition]()
  • 청원 배열을 저장할 속성을 ViewController에 만든다.

override func viewDidLoad() {
	super.viewDidLoad()
    
    let urlString = "https://www.hackingwithswift.com/samples.petitions-1.json"
    
    if let url = URL(string: urlString) {
    	if let data = try? Data(contentOf: url) {
        	parse(json: data)
        }
    }
}
  • whitehouse의 청원 서버에서 데이터를 다운로드하고, 이를 Swift Data 객체로 변환한 다음 이를 Petition 인스턴스의 배열로 변환하려한다.
  • urlString : 접근하려는 데이터
  • if let url = : URL이 유효한지 강제언래핑하지 않고 안전하게 확인하기 위해 if let 구문 사용
  • Data(contentOf: url) : contentOf 메서드를 가지는 Data 객체이다. URL에서 받은 콘텐츠를 반환한다.
    • 만약 인터넷 연결이 끊어진 경우 에러를 발생시킬 수 있기 때문에 try? 사용한다.

func parse(json: Data) {
	let decoder = JSONDecoder()
    
    if let jsonPetitions = try? decoder.decode(Petitions.self, from: json) {
    	petitions = jsonPetitions.results
        tableView.reloadData()
    }
}
  • let decoder = JSONDecoder() : JSON과 Codable객체 간의 변환을 위해 JSONDecoder인스턴스 생성
  • decoder.decode() : json데이터를 Petitions 객체로 변환하도록 요청한다. 작동여부를 확인하기 위해 try? 사용한다.
    • Petitions.self : 해당 인스턴스를 말하는 것이 아니라 Petitions 유형 자체를 참조한다는 의미이다.
  • JSON이 잘 변환되었으면 results 배열을 viewController의 petitions 속성에 할당한 다음 테이블 뷰를 다시 로드한다.

0개의 댓글