Getting JSON by using Alamofire and decode - Swift 4

人走茶凉 提交于 2019-12-13 14:01:35

问题


I have an API and I also want to get request.
But I try to using JSONDecoder to convert data type and I failed.
I don't know how to decode this Json like following data.
I want to take json["response"] contents setting my User struct.
Have any suggestion to me? Thanks.

Error Domain=NSCocoaErrorDomain Code=4865 "No value associated with key id ("id")." UserInfo={NSCodingPath=( ), NSDebugDescription=No value associated with key id ("id").}

This is JSON Data:

{
"status": "success",
"response": {
"id": "1130f1e48b608f79c5f350dd",
"name": "Jack",
},
"errors": ""
}


enum RestfulAPI:String {
    case userInfo = "http://www.mocky.io/v2/5a796fb92e00002a009a5a49"

    func get(parameters:[String : Any]? = nil,success:@escaping (_ response : Data)->(), failure : @escaping (_ error : Error)->()){
        let url = self.rawValue
        Alamofire.request(url, method: .get, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in
            switch response.result {
                case .success:
                if let data = response.data {
                    success(data)
                }
                case .failure(let error):
                    failure(error)
            }
       }
    }    
}

struct User: Decodable {
    let id: String
    let name: String
}

usage:

RestfulAPI.userInfo.get(success: { data in
     do {
         let user = try JSONDecoder().decode(User.self, from: data)
         print("==) ", user.id, user.name)
     }catch let error as NSError{
         print(error)
     }
 }) { (error) in
        print(error)
 }

回答1:


The key id is not on the level where you expect it. That's what the error message states.
The keys id and name are in the (sub)dictionary for key response.

So you need an umbrella struct

struct Root : Decodable {
   let status: String
   let response: User
}

struct User: Decodable {
    let id: String
    let name: String
}

Then decode

let root = try JSONDecoder().decode(Root.self, from: data)
let user = root.response


来源:https://stackoverflow.com/questions/48639299/getting-json-by-using-alamofire-and-decode-swift-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!