我是 swift 的新手,我在这方面遇到了麻烦。所以我需要做的是将这个数组保存为 iphone 的文档文件夹中的 json 文件。
var levels = ["unlocked", "locked", "locked"]
然后可以将其读回另一个数组。有人可以告诉我该怎么做吗?或提供完成此操作的确切代码。
编辑: 我找到了一个这样的例子。这是他们设置数据的方式:
"[ {"person": {"name":"Dani","age":"24"}}, {"person": {"name":"ray","age":"70"}} ]"
并且您可以通过这种方式访问它:
if let item = json[0]
{ if let person = item["person"]
{ if let age = person["age"]
{ println(age) } } }
但我需要能够从保存在文档文件夹中的文件执行相同的操作。
最佳答案
如果您像我一样不喜欢使用全新的第三方框架来处理这样微不足道的事情,那么这是我在 vanilla Swift 中的解决方案。从在 Documents 文件夹中创建 .json 文件到将 JSON 写入其中。
let documentsDirectoryPathString = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
let documentsDirectoryPath = NSURL(string: documentsDirectoryPathString)!
let jsonFilePath = documentsDirectoryPath.URLByAppendingPathComponent("test.json")
let fileManager = NSFileManager.defaultManager()
var isDirectory: ObjCBool = false
// creating a .json file in the Documents folder
if !fileManager.fileExistsAtPath(jsonFilePath.absoluteString, isDirectory: &isDirectory) {
let created = fileManager.createFileAtPath(jsonFilePath.absoluteString, contents: nil, attributes: nil)
if created {
print("File created ")
} else {
print("Couldn't create file for some reason")
}
} else {
print("File already exists")
}
// creating an array of test data
var numbers = [String]()
for var i = 0; i < 100; i++ {
numbers.append("Test\(i)")
}
// creating JSON out of the above array
var jsonData: NSData!
do {
jsonData = try NSJSONSerialization.dataWithJSONObject(numbers, options: NSJSONWritingOptions())
let jsonString = String(data: jsonData, encoding: NSUTF8StringEncoding)
print(jsonString)
} catch let error as NSError {
print("Array to JSON conversion failed: \(error.localizedDescription)")
}
// Write that JSON to the file created earlier
let jsonFilePath = documentsDirectoryPath.URLByAppendingPathComponent("test.json")
do {
let file = try NSFileHandle(forWritingToURL: jsonFilePath)
file.writeData(jsonData)
print("JSON data was written to teh file successfully!")
} catch let error as NSError {
print("Couldn't write to file: \(error.localizedDescription)")
}
关于json - 如何在 Swift 中将数组保存为 json 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28768015/