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

how to parse json data from local files?

我是 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,"=======") 
    }
}

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

你需要

struct Root: Codable {
    let brand: String
    let models: [String]
} 

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

你的问题

let JSON = try! JSONSerialization.jsonObject(with: data, options: []) 

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

请注意,代码中的变量 JSON 是一个对象数组。 你必须正确投射它。

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 , ".......")
    if let jsonArray = JSON as? [[String: Any]] {
        for item in jsonArray {
            let brand = item["brand"] as? String ?? "No Brand" //A default value
            print("=======",brand,"=======")
        }
    }
}