首页 > ios > 可解码的Json,功能根本不运行?

可解码的Json,功能根本不运行? (Decodable Json, function doesn't run at all?)

问题

我知道这个可解码的json问题已经被问了很多次,事实上我能够为我的其他项目进行数据的翻新。但是,我似乎无法让这个工作。IT部门假设检索数据,解码并存储数据。但是,我的打印功能从未运行过。我没有看到“已执行”的印刷品。它打印httpResponse与api的头文件,所以我知道它正在工作,它有一个响应。

解码

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()

        }

解决方法

从您的示例中,created_at不是字符串(它是一个数值),并且recommendation_id需要是可选的(与所有其他字段一样)。

此外,您的示例是单个记录,但您正在解码对象数组。将解码更改为JSONDecoder().decode(GetId.self, from: data!)

问题

I know this decodable json question has been asked a lot of times, in-fact i was able to do the retreival of data for one of my other projects. However, I cant seem to get this to work. IT is suppose to retrieve the data, decode it and store it. However, my print function was never ran. I don't see the "executed" print and moreover. It does print httpResponse with the headers from the api so I know it is working and it has a response.

Decodable

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?
}

Sample Response

{
    "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"
}

My function

    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()

        }

解决方法

From your example, created_at is not a string (it is a numeric value) and recommendation_id needs to be optional (like all the other fields).

Also, your example is a single record, but you are decoding an array of objects. Change the decode to be JSONDecoder().decode(GetId.self, from: data!)

相似信息