将数组存储到我在捆绑包中创建的answer.json文件中

时间:2019-04-20 07:22:41

标签: arrays json swift

在示例Xcode项目中,我创建了一个名为answer.json的json文件。 我想以编程方式向其写入数组。请帮我我的数组是

[["person": ["name": "Dani", "age": "24"]], ["person": ["name": "ray", "age": "70"]]]

 let fileUrl: String = Bundle.main.path(forResource: "answer",ofType:"json") as String!

 let personArray =  [["person": ["name": "Dani", "age": "24"]], ["person": ["name": "ray", "age": "70"]]]

 // Create a write-only stream
 guard let stream = OutputStream(toFileAtPath: fileUrl, append: false) else { return }
 stream.open()
 defer {
     stream.close()
 }

 // Transform array into data and save it into file
 var error: NSError?
 JSONSerialization.writeJSONObject(personArray, to: stream, options: [], error: &error)

 // Handle error
 if let error = error {
     print(error)
 }

我想在我的包路径中找到一个带有数组数据的json文件

1 个答案:

答案 0 :(得分:0)

您可以将其保存在“文档”目录中

guard let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
    let fileUrl = documentDirectoryUrl.appendingPathComponent("Persons.json")

    let personArray =  [["person": ["name": "Dani", "age": "24"]], ["person": ["name": "ray", "age": "70"]]]

    // Transform array into data and save it into file
    do {
        let data = try JSONSerialization.data(withJSONObject: personArray, options: [])
        try data.write(to: fileUrl, options: [])
    } catch {
        print(error)
    }