Decode Json Data using JsonDecoder and Alamofire

☆樱花仙子☆ 提交于 2019-12-11 08:34:37

问题


I am trying decode Json data into my Model. This is my model

struct Devices : Codable {
var id :String?
var description :String?
var status : Int?

}

 var heroes = Devices()
    print(DeviceId)
    let loginParam: [String: Any] = [
        "id": DeviceId
    ]
    let manager = Alamofire.SessionManager.default
    manager.session.configuration.timeoutIntervalForRequest = 5
    manager.request("http://13.13.13.004/website/api/Customer/DeviceControl", method: .post , parameters: loginParam, encoding: JSONEncoding.prettyPrinted)
        .responseData { response in
            let json = response.data

            do{
                let decoder = JSONDecoder()
                //using the array to put values
                heroes = try decoder.decode(Devices.self, from: json!)

            }catch let err{
                print(err)
            }

this code doesn't get in catch block. But heroes values return nill. When ı try use NsDictionary Its give result.


回答1:


This is a common mistake: You forget the root object

struct Root : Decodable {

    private enum  CodingKeys: String, CodingKey { case resultCount, devices = "results" }

    let resultCount : Int
    let devices : [Device]
}

And name the device struct in singular form (devices is an array of Device instances) and declare the members as non-optional

struct Device : Decodable {
    var id : String
    var description : String
    var status : Int
}

...

var heroes = [Device]()

...

let result = try decoder.decode(Root.self, from: json!)
heroes = result.devices


来源:https://stackoverflow.com/questions/52110124/decode-json-data-using-jsondecoder-and-alamofire

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