-1

这个问题类似于在嵌套的 NSDictionary 中替换 NSNull 的出现

在swift中我得到一个错误(我相信是因为NSNull的)我真的不在乎NSNull是变成空字符串还是零。我只是想让代码工作。

我有一个来自 JSON 作为 NSDictionary 的大型数据结构。然后我将其保存到一个临时文件中。这是代码:

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>";
            },
4

1 回答 1

1

更新:

问题:我有大量的 JSON(大约 600kb 作为文本)在该 JSON 数据中有空值。我遇到的问题是,当您将 NSJSONSerialization 作为 NSDictionary 时,它将空值转换为 NSNull 对象(如果您将其打印出来,它看起来很时髦,因为它们显示为字符串,这是错误的。

解决方案:您需要有一个“修剪过的”或“净化过的”字典。这意味着完全丢弃 key 和 value。为此,我添加了一个 sanitized_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

}

所以你的其他代码需要调用那个函数,它应该看起来像这样:

变量错误:NSError?

        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 数据集和空值的人。这都是关于消毒功能的!

于 2015-05-05T17:08:49.613 回答