我正在尝试创建一个与以下JSON字符串中的每个名称相关联的最新报告日期的数组。报告日期将不完全相同,如下所示,这将在更大的组中完成。最终,我还需要为第二,第三和第四报告日期创建数组。但我希望您可以在第一个数组上提供的任何清晰度都对创建其他数组有所帮助。
谢谢。
JSON字符串
[
{
"name": "John",
"records": [
{
"reportDate": "2018-07-20",
"hours": 204,
"billable": 32844
},
{
"reportDate": "2018-03-25",
"hours": 234,
"billable": 37715
}
]
},
{
"name": "Sam",
"records": [
{
"reportDate": "2018-06-18",
"hours": 187,
"billable": 13883
},
{
"reportDate": "2018-04-02",
"hours": 176,
"billable": 13467
}
]
}
]
结构
struct Employee : Decodable {
let name : String?
let records : [Record]
private enum CodingKeys: String, CodingKey {
case name = "name"
case records
}
struct Record : Decodable {
let reportDate : String?
let hours : Int?
let billable : Int?
private enum CodingKeys: String, CodingKey {
case reportDate = "reportDate"
case hours = "hours"
case billable = "billable"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
reportDate = try values.decodeIfPresent(String.self, forKey: .reportDate)
hours = try values.decodeIfPresent(Int.self, forKey: .hours)
billable = try values.decodeIfPresent(Int.self, forKey: .billable)
}
}
}
JSON解码小说
func downloadJSON( completed:@escaping ()->()){
guard let qurl = URL("https://website.com") else { return }
URLSession.shared.dataTask(with: qurl) { (data, response, error) in
if error == nil {
do{
self.employeeData = try JSONDecoder().decode([Employee].self, from: data!)
DispatchQueue.main.async{ completed() }
} catch { print("JSON Error") }
}
}.resume()
}