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는 청원들을 포함한다.
Swift 에는 JSON 작업을 지원하는 내장 프로토콜인 Codable이 있다.
String, Int 와 같은 기본 유형들은 자동으로 Codable을 따르고 배열과 딕셔너리들도 Codable객체를 포함하는 경우 Codable을 따른다.
- 즉 String이 Codable을 따르기 때문에 [String]도 Codable을 따른다
struct Petition {
var title: String
var body: String
var signatureCount: Int
}
struct Petition: Codable {
var title: String
var body: String
var signatureCount: Int
}
struct Petitions: Codable {
var results: [Petition]
}
var petitions = [Petition]()
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)
}
}
}
func parse(json: Data) {
let decoder = JSONDecoder()
if let jsonPetitions = try? decoder.decode(Petitions.self, from: json) {
petitions = jsonPetitions.results
tableView.reloadData()
}
}