如果数据嵌套在Swift中,如何解码响应数据

如果数据嵌套在Swift中,如何解码响应数据,swift,swift4,decodable,Swift,Swift4,Decodable,我在解码响应数据时遇到问题。这是我的请求函数 @IBAction func onGetCities(_ sender: UIButton) { guard let url = URL(string: "http://somelink.com/city-list") else { return } var request = URLRequest(url: url) request.httpMethod = "GET" let session = URLS

我在解码响应数据时遇到问题。这是我的请求函数

  @IBAction func onGetCities(_ sender: UIButton) {

    guard let url = URL(string: "http://somelink.com/city-list") else { return }

    var request = URLRequest(url: url)
    request.httpMethod = "GET"

    let session = URLSession.shared
    let task = session.dataTask(with: request) { (data, response, error) in


        print(JSON(data))
        guard let data = data else { return }
        do{
            let cities = try JSONDecoder().decode([City].self, from: data)
            print(cities)
        }catch{

        }
    }
    task.resume()
}
城市结构

struct City: Decodable {
    let id: Int
    let city: String
}
这是响应数据,我想解码“项目”


您需要具有反映嵌套JSON的嵌套结构:

struct City: Decodable {
    let id: Int
    let city: String
}

struct ResponseObject: Decodable {
    let items: [City]
    let offset: Int
    let limit: Int
}
然后:

do {
    let result = try JSONDecoder().decode(ResponseObject.self, from: data)
    print(result)

    let cities = result.items
    print(cities)
} catch {
    print(error)
}
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970

do {
    let result = try decoder.decode(ResponseObject.self, from: data)
    print(result)

    let cities = result.items
    print(cities)
} catch {
    print(error)
}

注意,在最初的示例中,您包含了一个JSON键,
updated_at
,它是自1970年以来以秒数表示的日期(标准UNIX表示)。因此,要解码:

struct City: Decodable {
    let id: Int
    let city: String
}

struct ResponseObject: Decodable {
    let items: [City]
    let offset: Int
    let limit: Int
    let code: Int
    let updatedAt: Date

    enum CodingKeys: String, CodingKey {
        case items, offset, limit, code
        case updatedAt = "updated_at"
    }
}
然后:

do {
    let result = try JSONDecoder().decode(ResponseObject.self, from: data)
    print(result)

    let cities = result.items
    print(cities)
} catch {
    print(error)
}
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970

do {
    let result = try decoder.decode(ResponseObject.self, from: data)
    print(result)

    let cities = result.items
    print(cities)
} catch {
    print(error)
}

还有一个问题,plz,建议使用吊舱吗?不。回到Swift 3,有些人会建议使用SwiftyJSON(虽然我个人从来都不喜欢),但
JSONDecoder
消除了这种需要。@AidogdyShahyrov-仅供参考,您修改后的问题对JSON做了一些修改,因此我在这里修改了代码以匹配。但希望它能说明基本思想,即使JSON格式的细节不太正确。感谢您从问题中删除代码屏幕快照!