Avatar ·

在Swift中读取JSON文件:适用于iOS 8及更新版本的分步指南

大家好!我是Swift和iOS开发的新手,在从文件读取JSON时遇到了问题。我正在开发一个简单的iOS 8应用,需要从本地JSON文件加载用户列表。文件名为`users.json`,位于项目文件夹中(我通过Xcode添加了它,它在导航器中可见)。 这是我的JSON内容: ```json { "users": [ {"id": 1, "name": "伊万", "email": "ivan@example.com"}, {"id": 2, "name": "玛丽亚", "email": "maria@example.com"} ] } ``` 我尝试使用`NSJSONSerialization`读取它,但总是遇到错误或得到nil。这是我的代码: ```swift if let path = NSBundle.mainBundle().pathForResource("users", ofType: "json") { if let jsonData = NSData(contentsOfFile: path) { do { let json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as? [String: AnyObject] print(json) } catch { print("JSON解析错误:\(error)") } } } ```