json - 如何在 Swift 中将数组保存为 json 文件?

标签 json xcode swift

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

相关文章:

ios - 使用 Swift 分析录制的音频文件以进行语音转文本

arrays - 如何使用嵌套数组解码 JSON 响应数组

javascript - Webpack4优化问题

ios - xcode 上的短信(有 MessageUI.framework),但仍然失败

ios - 推荐垃圾邮件移动应用程序

ios - Swift 4.0编译的模块无法导入Swift 3.2.2 : AudioKit

swift - 在 Swift 中评估定义 block 内的枚举

javascript - 如何检查本地存储数据集中是否存在值?

javascript - 如何在 ReactJs 中渲染 onclick 提交按钮的函数?

ios - 将 Xcode 更新到 12.5 和 iOS 更新到 14.5 后,React Native 0.64 不会构建 iOS 应用程序