在存储 NSDictionary 时出错,其中包含一些值,例如 swift 中的 userDefaults 中的 "<null>"


{
    deptId = 57f1fe3d3ac3aca0059d4d25;
    deptName = "Eagle Security";
    licences =         (
                    {
            "_id" = 57787880f9121e1b0516fb6b;
            name = "<null>";
        },
                    {
            "_id" = 57787881f9121e1b0516fb6c;
            name = "<null>";
        },
                    {
            "_id" = 57787883f9121e1b0516fb6d;
            name = " Mr.Apachu - SEC";
        },
                    {
            "_id" = 57787884f9121e1b0516fb6e;
            name = "Mr.John Peter - SEC";
        },
                    {
            "_id" = 578b3be488170556a2860a63;
            name = "Mr. Ramu - SEC";
        })}

我正在尝试将此Nsdictionary存储在UserDefaults中,但这给了我错误。一些好友能告诉我如何将其存储在用户默认值中。

do {
        let jsonData: Data = try JSONSerialization.data(withJSONObject: yourNSDictionary, options: .prettyPrinted)
        let strJson:String = String(data: jsonData, encoding: .utf8)!
        let strJsonWithNoNull = strJson.replacingOccurrences(of: "<null>", with: "")
        let data = strJsonWithNoNull.data(using: .utf8)!
        do {
            let dictonary = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any]
            if dictonary != nil
            {
                //you can store it inside user defaults
            }
        } catch let error as NSError {
            print(error)
        }

    } catch  let error as NSError {
        print(error)
    }

最新更新