如何解析本地文件中的json数据?

vgv*_*113 1 api json nsdictionary ios swift

我对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,"=======")
}
Run Code Online (Sandbox Code Playgroud)

当我如下修改此代码时

    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,"=======")
}
Run Code Online (Sandbox Code Playgroud)

然后我得到错误提示“ Type'Any'没有下标成员”

以下是我正在使用的json文件的示例

[{"brand": "Aston Martin", "models": ["DB11","Rapide","Vanquish","Vantage"]}]
Run Code Online (Sandbox Code Playgroud)

vad*_*ian 5

外部对象是一个数组,请注意,[]并且key的值models是一个String数组。

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,"=======") 
    }
}
Run Code Online (Sandbox Code Playgroud)

或更满意 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,"=======") 
    }
}
Run Code Online (Sandbox Code Playgroud)

通常,强烈建议不要使用强制解开可选选项,!但是在这种情况下,代码不得崩溃,因为应用程序捆绑包中的文件在运行时是只读的,任何崩溃都可能显示设计错误。


Sh_*_*han 5

你需要

struct Root: Codable {
    let brand: String
    let models: [String]
} 
Run Code Online (Sandbox Code Playgroud)
do {

     let url = Bundle.main.url(forResource: "car_list", withExtension: "json")!
     let data = try Data(contentsOf: url) 
     let res = try JSONDecoder().decode([Root].self, from: data)
     print(res)

}
catch { 
    print(error)
}
Run Code Online (Sandbox Code Playgroud)

你的问题是

let JSON = try! JSONSerialization.jsonObject(with: data, options: []) 
Run Code Online (Sandbox Code Playgroud)

返回Any,所以你不能在这里像字典一样使用下标JSON["brand"]