5

如帖子标题中所述,我在尝试快速将 Dictionary 转换为 JSON Data 时收到 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
        }

    }

我将字典作为参数传递,而不是出错。请帮帮我。

谢谢!

4

1 回答 1

3

请注意,您不需要所有这些东西,您的功能可能很简单:

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

如果你真的需要传递一个 Optional,那么你必须打开它:

func jsonEncode(object: Any?) -> Data? {
    if let object = object {
        return try? JSONSerialization.data(withJSONObject: object, options:[])
    }
    return nil
}
于 2016-12-01T13:12:12.253 回答