NSInvalidArgumentException-'JSON写入中的无效顶级类型'-Swift

iAk*_*kki 5 invalidargumentexception nsjsonserialization swift toplevel

如帖子标题中所述,尝试将字典快速转换为JSON数据时,我收到NSInvalidArgumentException-'JSON write中的无效顶级类型'

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

let inputData = jsonEncode(object: userInfo)
Run Code Online (Sandbox Code Playgroud)

。。。

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
        }

    }
Run Code Online (Sandbox Code Playgroud)

我将Dictionary作为参数传递,但没有出问题。请帮助我。

谢谢!

aya*_*aio 3

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

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

如果你确实需要传递一个Optional,那么你必须解开它:

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