使用Swift 4解码嵌套的JSON

时间:2018-06-03 06:59:27

标签: json swift swift4 decode

JSON =

{
"html_attributions": [],
"results": [
               {
                  "geometry": {},
                   "name": "Cruise Bar, Restaurant & Events",
                   "vicinity": "Circular Quay W, Sydney"
                },
                {}
],
"status": "OK"
}

如果名称嵌套在结果中,如何检索名称?

2 个答案:

答案 0 :(得分:0)

Sam尝试这个我使用你的Json在游乐场中编写示例代码。 root.results 会为您提供字典数组,您可以轻松遍历并从中获取所需的名称。

import UIKit

struct Root: Codable {
    let results: [Results]?

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

}

struct Results: Codable {
   let name: String?
   let vicinity: String?
}

let url = Bundle.main.url(forResource: "data", withExtension: "json")
let data = NSData(contentsOf: url!)


do {
      let root = try JSONDecoder().decode(Root.self, from: data as! Data)

      if let name = root.results?.first?.name {
          print(name)
      }    

} catch let error as NSError {

    print(error.description)
}

这是我用过的json。

{
"results": [{
            "name": "Cruise Bar, Restaurant & Events",
            "vicinity": "Circular Quay W, Sydney"
            }]
}

答案 1 :(得分:0)

你可以这样做:

<强>型号:

 import Foundation
struct HtmlInitial: Codable {
    let results: [Result]?
    let status: String

    enum CodingKeys: String, CodingKey {
        case results, status
    }
}

struct Result: Codable {
    let name, vicinity: String?
}

extension HtmlInitial {
    init(data: Data) throws {
        self = try JSONDecoder().decode(HtmlInitial.self, from: data)
    }
}

使用模型就像那样:

let url = Bundle.main.url(forResource: "APIResponse", withExtension: "json")!

if  let data = try? Data.init(contentsOf: url) ,
    let initial = try? HtmlInitial.init(data: data),
    let result = initial.results?[0] {
    print(result.name)
}