NSInvalidArgumentException - 'Invalid top-level type in JSON write' - Swift

NSInvalidArgumentException - 'Invalid top-level type in JSON write' - Swift

如 post 的标题中所述,我在尝试将 Dictionary 转换为 JSON swift[=14= 中的数据时收到 NSInvalidArgumentException - 'Invalid top-level type in JSON write' ]

let userInfo: [String: String] = [
            "user_name" : username!,
            "password" : password!,
            "device_id" : DEVICE_ID!,
            "os_version" : OS_VERSION
        ]

let inputData = jsonEncode(object: userInfo)

。 . .

static private func jsonEncode(object:Any?) -> Data?
    {
        do{
            if let encoded = try JSONSerialization.data(withJSONObject: object, options:[]) as Data?  <- here occured NSInvalidArgumentException

            if(encoded != nil)
            {
                return encoded
            }
            else
            {
                return nil
            }
        }
        catch
        {
            return nil
        }

    }

我将字典作为参数传递,没有弄错。请大家帮帮我。

谢谢!

请注意,您不需要所有这些东西,您的函数可以像这样简单:

func jsonEncode(object: Any) -> Data? {
    return try? JSONSerialization.data(withJSONObject: object, options:[])
}

如果你真的需要传递一个可选的,那么你必须解包它:

func jsonEncode(object: Any?) -> Data? {
    if let object = object {
        return try? JSONSerialization.data(withJSONObject: object, options:[])
    }
    return nil
}