我知道这个可解码的json问题已经问过很多次了,实际上我能够为其他项目之一进行数据检索。但是,我似乎无法使它正常工作。 IT假定要检索数据,对其进行解码并进行存储。但是,我的打印功能从未运行过。而且,我看不到“已执行”打印。它确实使用api的标头打印httpResponse,所以我知道它正在工作并且有响应。
可腐烂
struct GetId: Decodable {
let id : String?
let deck_id : String?
var completed_at : String?
let created_at : String?
let locale_key : String?
let profile_id : String?
let recommendation_id : String
let package_id : String?
let status : String?
let scoring_scale : String?
}
样品响应
{
"id": "XXXXXXX-XXX-4c6a-XXXX-1XXXXXXX223",
"deck_id": "career-deck",
"completed_at": null,
"created_at": 1551867228744,
"locale_key": "en-US",
"profile_id": "XXXXXXX-XXX-4c6a-XXXX-1XXXXXXX223",
"recommendation_id": null,
"package_id": null,
"status": "created",
"scoring_scale": "NORMAL"
}
我的功能
func requestId()
{
let headers = [
"Authorization": "Basic XXXxxxxXXxxXXXXxxxXXX:x",
"Content-Type": "application/json",
"cache-control": "no-cache"
]
let parameters = ["deck_id": "career-deck"] as [String : Any]
let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])
let request = NSMutableURLRequest(url: NSURL(string: "https://api.traitify.com/v1/assessments")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = (postData as! Data)
//let session = URLSession.shared
//let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
if let getIdd = try? JSONDecoder().decode([GetId].self, from: data!){
getId = getIdd
print(getId[0].id)
print("executed")
}
}
}
task.resume()
}
答案 0 :(得分:1)
在您的示例中,created_at
不是字符串(它是数字值),recommendation_id
必须是可选的(与所有其他字段一样)。
此外,您的示例是一条记录,但是您正在解码对象数组。将解码更改为JSONDecoder().decode(GetId.self, from: data!)