我希望API可以向我发送一些数据,我已经成功地检索到了它们,但是现在我在解码的过程中卡住了。 以下是我收到的JSON:
[
{
"challenge_id":1,
"challenge_title":"newchallenge1",
"challenge_pts_earned":1000,
"challenge_description":"description1",
"start_date":"2017-09-24T00:00:00.000Z",
"end_date":"2017-09-24T00:00:00.000Z",
"challenge_category_id":1,
"status_id":2,
"createdAt":"2017-09-24T17:21:47.000Z",
"updatedAt":"2017-09-24T09:40:34.000Z"
},
{
"challenge_id":2,
"challenge_title":"challenge1",
"challenge_pts_earned":100,
"challenge_description":"description1",
"start_date":"2017-09-24T00:00:00.000Z",
"end_date":"2017-09-24T00:00:00.000Z",
"challenge_category_id":1,
"status_id":0,
"createdAt":"2017-09-24T17:22:12.000Z",
"updatedAt":"2017-09-24T09:22:12.000Z"
},
{
"challenge_id":3,
"challenge_title":"new eat title",
"challenge_pts_earned":600000,
"challenge_description":"haha",
"start_date":"2017-01-09T00:00:00.000Z",
"end_date":"2017-01-10T00:00:00.000Z",
"challenge_category_id":2,
"status_id":0,
"createdAt":"2017-09-27T17:12:10.000Z",
"updatedAt":"2017-09-27T09:15:19.000Z"
}
]
我正在尝试创建以下结构来解码它:
struct challenge : Codable {
let id : String?
let title : String?
let pointsEarned : String?
let description : String?
let dayStarted : String?
let dayEnded : String?
let categoryID : String?
let statusID : Int?
let createdAt : Date?
let updatedAt : Date?
enum CodingKeys: String, CodingKey {
case id = "challenge_id"
case title = "challenge_title"
case pointsEarned = "challenge_pts_earned"
case description = "challenge_description"
case dayStarted = "start_date"
case dayEnded = "end_date"
case categoryID = "challenge_category_id"
case statusID = "status_id"
case createdAt, updatedAt
}
}
下面是我的代码实现:
var All_challenges : [challenge]?
let url = URL(string: API.all_challenges.rawValue)!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("\(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
guard let result = responseString else { return }
print(result)
if let json = try? JSONDecoder().decode([challenge].self , from : data ) {
self.All_challenges = json
}
}
task.resume()
然而,当我尝试调试它时,我永远无法进入if语句。
if let json = try? JSONDecoder().decode([challenge].self,from:data ) {
self.All_challenges = json
}
请帮我指出我的错误,我对JSON解析非常陌生。
try?
抛弃解码错误,而是捕获错误并将其打印出来;它会告诉你问题的具体所在。 - HamishUpperCamelCase
,而属性和变量名称应为lowerCamelCase
(从不使用snake_case
)。如果您的JSON键名不同,您可以定义一个自定义的CodingKeys
枚举。此外,所有属性都需要是可选的吗?如果给定的键值在JSON中始终存在,则将其设置为非可选项。 - Hamish