Swift 使用JsonDecoder和Alamofire解码Json数据

Swift 使用JsonDecoder和Alamofire解码Json数据,swift,alamofire,jsondecoder,Swift,Alamofire,Jsondecoder,我正在尝试将Json数据解码到我的模型中。 这是我的模型 struct Devices : Codable { var id :String? var description :String? var status : Int? } 此代码不在catch块中。 但英雄的价值观是零。 当ı尝试使用NsDictionary 这是一个常见的错误:您忘记了根对象 struct Root : Decodable { private enum CodingKeys: String, Codin

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

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

此代码不在catch块中。 但英雄的价值观是零。 当ı尝试使用NsDictionary
这是一个常见的错误:您忘记了根对象

struct Root : Decodable {

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

    let resultCount : Int
    let devices : [Device]
}
并以单数形式命名设备结构(
devices
device
实例的数组),并将成员声明为非可选成员

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

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

struct Root : Decodable {

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

    let resultCount : Int
    let devices : [Device]
}
并以单数形式命名设备结构(
devices
device
实例的数组),并将成员声明为非可选成员

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

您可以这样做:
让jsonString=String(数据:json,编码:.utf8);打印(“JSON:\(jsonString)
并告诉我们输出结果是什么?@Larme its give correct result
JSON:Optional(“{\”resultCount\”:1,\“results\”:[{\”id\”:“haktaneb\”,“status\”:0,\“description\”:“asfasf\”))}”)
你能做什么:
让jsonString=String(数据:JSON,编码:.utf8);打印(“JSON:\”(JSON:(jsonString)
并告诉我们输出是什么?@Larme its give correct result
JSON:Optional({“resultCount\”:1,“results\”:[{“id\”:“haktaneb\”,“status\”:0,“description\”:“asfasf\”)
获取此错误
类型不匹配(Swift.Dictionary,Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue:“results”,intValue:nil)],debugDescription:“应解码字典,但找到了一个数组。”,underlineError:nil))
答案中的代码与注释中的JSON完全对应。错误表示您要解码
let results:Device
(不带括号)。获取此错误
类型不匹配(Swift.Dictionary,Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue:“results”,intValue:nil)],debugDescription:“应解码字典,但找到了数组。”,underyingerror:nil))
答案中的代码与注释中的JSON完全对应。错误表示您要解码
let results:Device
(不带括号)。