使用JsonDecoder和Alamofire解码Json数据 [英] Decode Json Data using JsonDecoder and Alamofire

查看:93
本文介绍了使用JsonDecoder和Alamofire解码Json数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Json数据解码到我的模型中。
这是我的模型

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

此代码不会进入catch块。
但是英雄值返回nill。
当我尝试使用 NsDictionary
给出结果时。

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

推荐答案

此这是一个常见的错误:您忘记了根对象

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

并以单数形式命名设备结构( devices 是<$ c的数组$ c> 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

这篇关于使用JsonDecoder和Alamofire解码Json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆