iOS中如何在Documents目录保存与读取JSON文件?
iOS中Documents目录的JSON文件读写操作
核心思路
JSON文件的读写本质是JSON对象与Data的互相转换,结合Documents目录的文件操作即可完成流程:先把JSON对象(字典/数组)转成Data写入文件,读取时再把文件Data转回JSON对象。
1. 获取Documents目录路径
先拿到iOS沙盒中Documents目录的URL,这是所有文件操作的基础:
func getDocumentsDirectory() -> URL { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return paths[0] }
2. 保存JSON到Documents目录
将JSON对象([AnyHashable: Any]或[Any])序列化为Data,再写入指定文件名的文件:
// 保存字典类型的JSON func saveDictionaryJSON(to fileName: String, json: [AnyHashable: Any]) { let fileURL = getDocumentsDirectory().appendingPathComponent(fileName) do { // .prettyPrinted 可选,让JSON格式化输出方便查看;用[]则是压缩格式 let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) try jsonData.write(to: fileURL) print("JSON文件已成功保存到Documents") } catch { print("保存失败:\(error.localizedDescription)") } } // 保存数组类型的JSON func saveArrayJSON(to fileName: String, json: [Any]) { let fileURL = getDocumentsDirectory().appendingPathComponent(fileName) do { let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) try jsonData.write(to: fileURL) print("数组类型JSON保存成功") } catch { print("保存失败:\(error.localizedDescription)") } }
使用示例
// 示例字典JSON let userData: [String: Any] = [ "username": "Emanuele Mele", "email": "example@test.com", "isActive": true, "loginCount": 12 ] saveDictionaryJSON(to: "userProfile.json", json: userData) // 示例数组JSON let taskList: [Any] = [ ["title": "完成iOS开发", "status": "done"], ["title": "整理JSON文档", "status": "pending"] ] saveArrayJSON(to: "tasks.json", json: taskList)
3. 从Documents目录读取JSON
读取文件Data,再反序列化为JSON对象:
// 读取字典类型JSON func loadDictionaryJSON(from fileName: String) -> [AnyHashable: Any]? { let fileURL = getDocumentsDirectory().appendingPathComponent(fileName) do { let jsonData = try Data(contentsOf: fileURL) guard let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [AnyHashable: Any] else { print("JSON格式不匹配,无法转成字典") return nil } return json } catch { print("读取失败:\(error.localizedDescription)") return nil } } // 读取数组类型JSON func loadArrayJSON(from fileName: String) -> [Any]? { let fileURL = getDocumentsDirectory().appendingPathComponent(fileName) do { let jsonData = try Data(contentsOf: fileURL) guard let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [Any] else { print("JSON格式不匹配,无法转成数组") return nil } return json } catch { print("读取失败:\(error.localizedDescription)") return nil } }
使用示例
// 读取字典JSON if let loadedUser = loadDictionaryJSON(from: "userProfile.json") { print("读取到用户数据:\(loadedUser)") let username = loadedUser["username"] as? String ?? "" print("用户名:\(username)") } // 读取数组JSON if let loadedTasks = loadArrayJSON(from: "tasks.json") { print("读取到任务列表:\(loadedTasks)") for task in loadedTasks { if let taskDict = task as? [String: String] { print("任务标题:\(taskDict["title"] ?? ""),状态:\(taskDict["status"] ?? "")") } } }
注意事项
- JSONSerialization仅支持JSON兼容类型:字符串、数字、布尔值、数组、字典、
NSNull,自定义对象需要先转成字典/数组再序列化。 - 如果需要更类型安全的操作,也可以使用
Codable协议,本质仍是转Data完成文件读写,只是序列化方式不同。
内容的提问来源于stack exchange,提问作者Emanuele Mele
相关产品推荐
相关产品推荐

