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

无人久伴 提交于 2019-12-10 14:56:34

问题


As mentioned in the title of post,I'm getting NSInvalidArgumentException - 'Invalid top-level type in JSON write' when trying to convert Dictionary to JSON Data in swift

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
        }

    }

I'm passing Dictionary as parameter, not getting whats going wrong. Please help me guys.

Thanks!


回答1:


Note that you don't need all this stuff, your function could be as simple as:

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

If you really need to pass an Optional, then you have to unwrap it:

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


来源:https://stackoverflow.com/questions/40911333/nsinvalidargumentexception-invalid-top-level-type-in-json-write-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!