json - 无法通过可编码的swift从json中获取数据

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

最佳答案

替换

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

你的根是字典而不是数组

关于json - 无法通过可编码的swift从json中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53977577/

相关文章:

python - Scrapy yield 项目作为 JSON 中的子项目

javascript - 在 div 中显示 json html 数据

如果文本长于两行,Swift UITextView 会更改字体大小

objective-c - Objective-C 类中的 Swift 协议(protocol)

json - Swift 4 可编码;如何使用单个根级 key 解码对象

json - 如何从 JSON 对象 Swift 4 中检索值

javascript - jQuery 到 Wordpress - Uncaught Error 让我发疯

javascript - 跨域json请求可以设置header吗?

ios - XCode Fix-it 建议强制解包 bool 值?

Swift Generic 不显示 nil