有时候,想自己生成JSON文件或者其他..可以把字典或者数组转成JSON
struct MySnail {
// 字典或者数组 转 JSON
static func dataTypeTurnJson(element:AnyObject) -> String {
let jsonData = try! NSJSONSerialization.dataWithJSONObject(element, options: NSJSONWritingOptions.PrettyPrinted)
let str = String(data: jsonData, encoding: NSUTF8StringEncoding)!
//路径
let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let filePath = path.stringByAppendingString("/data666.json")
try! str.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding)
print(filePath) //取件地址 点击桌面->前往->输入地址跳转取件
return str
}
} //注意这里还未对异常进行处理,只是方便大家转成JSON本地文件
使用例子:
let myArr = ["a":[["name": "阿坝", "pinyin": "aba"], ["name": "阿克苏", "pinyin": "akesu"], ["name": "阿拉善", "pinyin": "alashanmeng"], ["name": "阿勒泰", "pinyin": "aletai"]]]
let jsonStr = MySnail.dataTypeTurnJson(myArr) //打印下,看调式窗口
jsonStr
根据收件地址前往 Json文件Json文件
网友评论