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

编程入门 行业动态 更新时间:2024-10-27 06:27:54
本文介绍了如何在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文件?

本文发布于:2023-07-27 03:09:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1219991.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   另存为   中将   文件   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!