如果数据嵌套在Swift

时间:2018-02-25 21:24:17

标签: 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 = 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()
}

和City struct

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

这是响应数据,我想解码“items”

{
"offset": 0,
"limit": 10,
"items": [
  {id: 0, name: "City name"},
  {id: 1, name: "City name1"},
  .....
]

}

1 个答案:

答案 0 :(得分:2)

您需要具有镜像嵌套JSON的嵌套结构:

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

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

然后:

updated_at

请注意,在您的原始示例中,您包含了一个JSON密钥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" } } ,它是自1970年以来以秒数表示的日期(标准UNIX表示)。所以,解码一下:

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

然后:

$(window).load(function () {
 //something