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

标签 ios json swift api nsdictionary

我对 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/

相关文章:

ios - iOS 7-UITextView剪辑文本

javascript - 从单行中的嵌套 JSON 对象获取数据

python - 转json还是不转json

swift - 在 viewDidAppear 中快速淡入数据

ios - UIVisualEffectView 和 UITableViewCell 内部的触摸

ios - UITableViewController 和 TableView 高度

ios - uitextfield 在按下 delete 时清除

ios - Storyboard如何推送嵌套导航 Controller ?

ios - 'NSMutableDictionary'没有可见的@interface声明选择器 'addObjects:forKey'

java - 来自 StackExchange API 的 JSON URL 返回乱码?