无法通过可编码的Swift从JSON获取数据

时间:2018-12-30 12:26:11

标签: json swift codable

这是json代码:

{
  "status":"success",
   "data":
     [
       {"id":"3",
        "city_name":"Delhi",
         "city_image":"delhi.png"},
       {"id":"4",
        "city_name":"Mumbai",
        "city_image":"tickmark.png"}
     ]
 }

我的Swift代码:

struct city: Decodable{
    let status : String
    let id: String
    let data : String
    let city_name: String
    let city_image: String
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let jsonUrl = "http://parking.onlinekiduniya.org/api/cityList.php"
        let url = URL(string: jsonUrl)
        URLSession.shared.dataTask(with: url!) {(data, response, error) in
            do {
                let cities = try JSONDecoder().decode([city].self, from: data!)
                for city in cities {
                print(city.id)
            }
            }
            catch {
                print("we got error")
        }
        }.resume()
    }
}

1 个答案:

答案 0 :(得分:1)

替换

let cities = try JSONDecoder().decode([city].self, from: data!)

使用

let root = try JSONDecoder().decode(Root.self, from: data!)
let cities = root.data
cities.forEach {
   print($0.id)
}

struct Root: Codable {
    let status: String
    let data: [City]
}

struct City: Codable {
    let id, cityName, cityImage: String // you can use snake case also

    enum CodingKeys: String, CodingKey {
        case id
        case cityName = "city_name"
        case cityImage = "city_image"
    }
}

您的根是字典,而不是数组