Akshay Gajarlawar Akshay Gajarlawar - 1 year ago 71
Swift Question

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

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{
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!

Answer Source

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
}