Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 992
iAkshay Avatar asked Oct 17 '22 21:10

iAkshay


1 Answers

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
}
like image 95
Eric Aya Avatar answered Nov 30 '22 22:11

Eric Aya