我的Web服务使用此信息进行响应
[ { "IdWeek": 18340, "DateInit": "2018-08-19T00:00:00", "DateEnd": "2018-08-25T00:00:00", "TotalDays": 7, "WeekNumber": "34", "WeekDescription": "Semana del: 19/08/2018 al: 25/08/2018", "Status": 0, "IdWeekAccuredInit": 0, "IdWeekAccuredEnd": 0, "DateAccuredInit": "0001-01-01T00:00:00", "DateAccuredEnd": "0001-01-01T00:00:00" }, { "IdWeek": 18330, "DateInit": "2018-08-12T00:00:00", "DateEnd": "2018-08-18T00:00:00", "TotalDays": 7, "WeekNumber": "33", "WeekDescription": "Semana del: 12/08/2018 al: 18/08/2018", "Status": 0, "IdWeekAccuredInit": 0, "IdWeekAccuredEnd": 0, "DateAccuredInit": "0001-01-01T00:00:00", "DateAccuredEnd": "0001-01-01T00:00:00" },
我想将这些值保存在名为Week的对象类中,但是我的任务出错。
class Week : Decodable
{
let IdWeek:String
let DateInit:Date
let DateEnd:Date
let TotalDays:Int
let WeekNumber:String
let WeekDescription:String
let Status:Int
let IdWeekAccuredInit:Int
let IdWeekAccuredEnd:Int
let DateAccuredInit:Date
let DateAccuredEnd:Date
}
DispatchQueue.main.sync(execute: {
do
{
//let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
guard let weeks = try? JSONDecoder().decode(Week.self, from: data)
else
{
print("Error: No puede decodificar en Weeks")
return
}
for idWeek in weeks.IdWeek
{
print("idSemana:\(idWeek)")
}
print("Creando Objeto JSON")
//print(json)
}
catch
{
print("El procesamiento del JSON tuvo un Error")
}
})
答案 0 :(得分:0)
您的JSON是一个数组,因此您需要:
guard let weeks = try? JSONDecoder().decode([Week.self], from: data)
另外,不要大写您的属性,Swift约定是使用驼峰式大小写。