您可以保存json数据而不进行存档

时间:2015-07-21 06:45:45

标签: json swift

我想将json数据保存到文件中而不进行存档。这样我就可以打开文件并检查一切是否正常

// valid json data
if NSJSONSerialization.isValidJSONObject(jsonData) {

    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
    let documentsDirectory = paths[0] as! String
    let path = documentsDirectory.stringByAppendingPathComponent("test.json")
    println(path) // if I open the file from finder, all the data is archived


    // try 1: the jsonData is archived
    if NSKeyedArchiver.archiveRootObject(jsonData, toFile: path) {
        println("saved: true");
    }

    let stringTest = "asd"
    stringTest.writeToFile(path, atomically: true, encoding: NSStringEncoding.allZeros, error: nil)
    // the string is also archived

}

我也试试

var jsonNSData = NSKeyedArchiver.archivedDataWithRootObject(jsonData)
var string = NSString(data: jsonNSData, encoding: NSUTF8StringEncoding)
println(string) // returns nil

2 个答案:

答案 0 :(得分:1)

您可以将JSON转换为NSDictionary,然后将其写入用户文档目录:

var someJsonAsDict: [String: AnyObject] = ["foo": "string", "bar": NSNumber(integer: 5)]

if let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as? [String],
    let documentsDirectory = paths.first
{
    let filePath = documentsDirectory.stringByAppendingPathComponent("myPlistFile")
    let fileManager = NSFileManager.defaultManager()

    //IMPORTANT - someJsonAsDict cannot have primite types(they must be boxed in Appropriate NSNumber, NSValue, etc)
    (someJsonAsDict as NSDictionary).writeToFile(filePath, atomically: true)

    //print path of simulator so you can read it from terminal
    println("target path is \(filePath)")
}

如果碰巧将Array作为JSON的最外层对象,只需替换:

someJsonAsDict as NSDictionary

使用适当的数组方法:

someJsonAsDict as NSArray

所有这些都将使用JSON创建plist文件。如果您碰巧需要原始json样式(如txt),您可以使用plutil(与Xcode命令行工具一起安装):

plutil -convert json myPlistFile.plist -o MyTxtFile.json

答案 1 :(得分:0)

也许您可以使用NSUserDefaults来存档值。比如var save = NSUserdefaults.userdefaults()然后var ValueSaved = save.setObject(stringTest, "StringTest")这是归档文件的最简单模式..但它不会归档到文件中:\