【问题标题】:Decode Json Data using JsonDecoder and Alamofire使用 JsonDecoder 和 Alamofire 解码 Json 数据
【发布时间】:2019-02-06 04:07:20
【问题描述】:

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

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 块。 但是英雄值返回零。 当我尝试使用 NsDictionary 给出结果。

【问题讨论】:

  • 你能不能:let jsonString = String(data: json, encoding: .utf8); print("JSON: \(jsonString) 并告诉我们输出是什么?
  • @Larme 给出正确的结果JSON: Optional("{\"resultCount\":1,\"results\":[{\"id\":\"haktaneb\",\"status\":0,\"description\":\"asfasf\"}]}")

标签: swift alamofire jsondecoder


【解决方案1】:

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

struct Root : Decodable {

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

    let resultCount : Int
    let devices : [Device]
}

并以单数形式命名设备结构(devicesDevice 实例的数组)并将成员声明为非可选

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

【讨论】:

  • 收到此错误typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "results", intValue: nil)], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))
  • 答案中的代码与评论中的JSON完全对应。错误说你想解码let results : Device(不带括号)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-10
  • 2018-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-20
相关资源
最近更新 更多