我对 json 解析很陌生,并试图解析一个包含汽车列表的 json 文件,但是当我解析时,它给出了 nil
func jsonTwo(){
let url = Bundle.main.url(forResource: "car_list", withExtension: "json")!
let data = try! Data(contentsOf: url)
let JSON = try! JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
print(".........." , JSON , ".......")
let brand = JSON?["models"] as? [[String : Any]]
print("=======",brand,"=======")
}
当我对这段代码进行如下修改时
func jsonTwo(){
let url = Bundle.main.url(forResource: "car_list", withExtension: "json")!
let data = try! Data(contentsOf: url)
let JSON = try! JSONSerialization.jsonObject(with: data, options: [])
print(".........." , JSON , ".......")
let brand = JSON["brand"] as? [[String : Any]]
print("=======",brand,"=======")
}
然后我得到错误提示“Type 'Any' has no subscript members”
下面是我正在使用的 json 文件的示例
[{"brand": "Aston Martin", "models": ["DB11","Rapide","Vanquish","Vantage"]}]
最佳答案
外部对象是一个数组,请注意 []
键 models
的值是一个字符串数组。
func jsonTwo() {
let url = Bundle.main.url(forResource: "car_list", withExtension: "json")!
let data = try! Data(contentsOf: url)
let json = try! JSONSerialization.jsonObject(with: data) as! [[String : Any]]
print(".........." , JSON , ".......")
for item in json {
let brand = item["brand"] as! String
let models = item["models"] as! [String]
print("=======",brand, models,"=======")
}
}
或更熟悉 Decodable
struct Car: Decodable {
let brand : String
let models : [String]
}
func jsonTwo() {
let url = Bundle.main.url(forResource: "car_list", withExtension: "json")!
let data = try! Data(contentsOf: url)
let cars = try! JSONDecoder().decode([Car].self, from: data)
for car in cars {
let brand = car.brand
let models = car.models
print("=======",brand, models,"=======")
}
}
通常,强烈建议您不要使用 !
强制解包可选值,但在这种情况下,代码不能崩溃,因为应用程序包中的文件在运行时是只读的,任何崩溃都会显示 < strong>设计错误。
关于ios - 如何解析本地文件中的json数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54089660/