如何在Swift中将数组另存为json文件? [英] How to save an array as a json file in Swift?

查看:107
本文介绍了如何在Swift中将数组另存为json文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手,遇到了麻烦.所以我需要做的就是将此数组另存为json文件到iphone的文档文件夹中.

I'm new at swift and I'm having trouble with this. so what i need to do is save this array as a json file in the document folder of the iphone.

var levels = ["unlocked", "locked", "locked"]

,然后可以将其读回到另一个数组中.有人可以告诉我该怎么做吗?或提供完成此操作的确切代码.

and then later on be able to read it back into another array. Could someone please tell me how to do this? or provided with the exact code to accomplish this.

我找到了一个例子.他们是如何设置数据的:

EDITED: I found one example of this. This is how they set up the data:

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

,您可以通过以下方式访问它:

and the you can access it this way:

 if let item = json[0] 
   { if let person = item["person"] 
     { if let age = person["age"] 
      { println(age) } } }

但是我需要能够执行同样的操作,但是需要保存在文档文件夹中的文件中.

But I need to be able to do the same but from a file that is saved on the document folder.

推荐答案

我建议您使用 SwiftyJSON 框架.研究其文档,另外学习如何将字符串写入文件(提示:NSFileHandle)

I recommend that you use SwiftyJSON framework. Study its documentation and in addition learn how to write strings to files (hint: NSFileHandle)

类似下面的代码,但是您确实需要学习SwiftyJSON和NSFileHandle来学习如何将JSON数据序列化到文件以及从文件中解析JSON数据

Something like the code below, but you really need to study both SwiftyJSON and NSFileHandle to learn how to both serialize JSON data to a file and parse JSON data from a file

let levels = ["unlocked", "locked", "locked"]
let json = JSON(levels)
let str = json.description
let data = str.dataUsingEncoding(NSUTF8StringEncoding)!
if let file = NSFileHandle(forWritingAtPath:path) {
    file.writeData(data)
} 

这篇关于如何在Swift中将数组另存为json文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆