我正在尝试解码JSON。我用于解码JSON的快捷功能是:
func GetChapInfo(){
let endpoint = "https://chapel-logs.herokuapp.com/chapel"
let endpointUrl = URL(string: endpoint)
do {
var request = URLRequest(url: endpointUrl!)
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = URLSession.shared.dataTask(with: request){
(data: Data?, response: URLResponse?, error: Error?) in
let dataAsString = String(data: data!, encoding: .utf8)
//print(dataAsString)
if(error != nil) {
print("Error")
}
else{
do{
guard let chapData = try? JSONDecoder().decode(Chapel.self, from: data!) else {
print("Error: Couldn't decode data into chapData")
return
}
for E in chapData.chap {
print(E.Day as Any)
}
}
}
}
task.resume()
}
}
我在Swift中的struct
是
struct Chapel: Decodable {
let chap: [Chap]
}
struct Chap: Decodable {
let Name: String?
let Loc: String?
let Year: Int?
let Month: Int?
let Day: Int?
let Hour: Int?
let Min: Int?
let Sec: Int?
}
服务器发出的响应是:
{"chap":{"Name":"Why Chapel","Loc":"FEC","Year":2018,"Month":9,"Day":4,"Hour":16,"Min":1,"Sec":7}}
但是,当我运行此程序时,程序会打印出“错误:无法将数据解码为chapData”,我无法弄清原因。
答案 0 :(得分:2)
首先 catch
解码错误。永远不要try?
。捕获的错误更具描述性
打算解码
Array<Any>
,但找到了字典
方法:键chap
的值是一个字典,而不是数组
struct Chapel: Decodable {
let chap: Chap
}
然后您必须打印
print(chapData.chap.Day)
您可以减少代码。不需要显式的URLRequest
和默认GET请求的标头。足够了:
let endpoint = "https://chapel-logs.herokuapp.com/chapel"
let endpointUrl = URL(string: endpoint)!
do {
let task = URLSession.shared.dataTask(with: endpointUrl) { (data, response, error) in
...