Cocoa 在NSDictionary中替换NSNulls
这个问题类似于 在swift中,我得到了一个错误(我相信是因为NSNull),我并不在乎NSNull是变成空字符串还是nil。我只是想让代码正常工作 我有一个来自JSON的大型数据结构作为NSDictionary。然后我将它保存到一个临时文件中。代码如下:Cocoa 在NSDictionary中替换NSNulls,cocoa,swift,nsdictionary,nsnull,Cocoa,Swift,Nsdictionary,Nsnull,这个问题类似于 在swift中,我得到了一个错误(我相信是因为NSNull),我并不在乎NSNull是变成空字符串还是nil。我只是想让代码正常工作 我有一个来自JSON的大型数据结构作为NSDictionary。然后我将它保存到一个临时文件中。代码如下: var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as! NSDiction
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as! NSDictionary
let json = JSON(jsonResult)
if (json["errors"].array?.count > 0) {
println("could not load stuff")
} else {
println("retrieving the stuff")
let file = "file.txt"
let file_path = NSTemporaryDirectory() + file
let dict:NSDictionary = jsonResult
let readDict:NSDictionary? = NSDictionary(contentsOfFile: file_path)
if dict.writeToFile(file_path, atomically: true) {
let readDict:NSDictionary? = NSDictionary(contentsOfFile: file_path)
//--- need to handle the NSNull junk here
if let dict = readDict {
println("Temp file created, here are the contents: \(dict)")
} else {
println("!!!Failed to READ the dictionary data back from disk.")
}
}
else {
println("!!!Failed to WRITE the dictionary to disk.")
}
}
下面是一个jsonResult的示例
things = (
{
"one" = one;
two = "<null>";
"three" = three;
"four" = "<null>";
"five" = five;
"six" = "six-6";
seven = 7;
eight = eight;
nine = "<null>";
ten = "<null>";
eleven = "<null>";
"twelve" = "<null>";
},
事物=(
{
“一”=一;
两个“”;
“三”=三;
“四”=”;
“五”=五;
“六”=“六-6”;
七=7;
八=八;
“九”;
“十”;
11=“”;
“十二”;
},
更新:
问题:我的JSON数据中有大量的JSON(大约600kb为文本),其中有空值。我遇到的问题是,当您将NSJSONSerialization作为NSDictionary时,它会将空值转换为NSNull对象(如果您将其打印出来,因为它们显示为字符串,这看起来很奇怪,这是错误的)
解决方案:您需要一个“删减”或“净化”字典。这意味着完全丢弃键和值。为此,我添加了一个净化的dict函数。函数如下:
func sanitize_dict(obj: AnyObject) -> AnyObject {
if obj.isKindOfClass(NSDictionary) {
var saveableObject = obj as! NSMutableDictionary
for (key, value) in obj as! NSDictionary {
if (value.isKindOfClass(NSNull)) {
//println("Removing NSNull for: \(key)")
saveableObject.removeObjectForKey(key)
}
if (value.isKindOfClass(NSArray)) {
let tmpArray: (AnyObject) = sanitize_dict(value as! NSArray)
saveableObject.setValue(tmpArray, forKey: key as! String)
}
if (value.isKindOfClass(NSDictionary)) {
let tmpDict: (AnyObject) = sanitize_dict(value as! NSDictionary)
saveableObject.setValue(tmpDict, forKey: key as! String)
}
}
return saveableObject
//--- because arrays are handled differently,
//--- you basically need to do the same thing, but for an array
//--- if the object is an array
} else if obj.isKindOfClass(NSArray) {
var saveableObject = [AnyObject]()
for (index, ele) in enumerate(obj as! NSArray) {
if (ele.isKindOfClass(NSNull)) {
// simply don't add element to saveableobject and we're good
}
if (ele.isKindOfClass(NSArray)) {
let tmpArray: (AnyObject) = sanitize_dict(ele as! NSArray)
saveableObject.append(tmpArray)
}
if (ele.isKindOfClass(NSDictionary)) {
let tmpDict: (AnyObject) = sanitize_dict(ele as! NSDictionary)
saveableObject.append(tmpDict)
}
}
return saveableObject
}
// this shouldn't happen, but makes code work
var saveableObject = [AnyObject]()
return saveableObject
}
因此,您的其他代码需要调用该函数,它应该如下所示:
变量错误:n错误
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as! NSDictionary
//--- right now jsonResult is not actual json, and actually has the NSNulls
//--- get that result into the sanitized function above
let saveableDict: (AnyObject) = self.sanitize_dict(jsonResult)
let json = JSON(saveableDict)
if (json["errors"].array?.count > 0) {
println("!!!Failed to load.")
} else {
println("Load json successful. Attempting to save file...")
//--- set up basic structure for reading/writing temp file
let file = "file.txt"
let file_path = NSTemporaryDirectory() + file
let dict:NSDictionary = jsonResult
let readDict:NSDictionary? = NSDictionary(contentsOfFile: file_path)
if dict.writeToFile(file_path, atomically: true) {
let readDict:NSDictionary? = NSDictionary(contentsOfFile: file_path)
if let dict = readDict {
println("Temp file created, here are the contents: \(dict)")
} else {
println("!!!Failed to READ the dictionary data back from disk.")
}
}
else {
println("!!!Failed to WRITE the dictionary to disk.")
}
}
希望这能在JSON数据集和空值方面对其他人有所帮助。这都是关于清理功能的!“在swift中,我遇到了一个错误(我相信是因为NSNull的错误)”–你为什么这么认为?JSON看起来像什么?你会得到什么错误?@Martinar看着jsonResult,看起来这就是问题所在。有没有办法强制所有东西都是字符串?我知道因为writeFile,所有的键都必须是字符串。我在主帖子中放了一个jsonResult看起来像什么的示例。我是also前一段时间收到“致命错误:在展开可选值时意外发现nil”(出于某种原因,我不再收到该错误)