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

标签 swift nsjsonserialization toplevel invalidargumentexception

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

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
        }

    }

我将字典作为参数传递,没有弄错。请帮帮我。

谢谢!

最佳答案

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

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
}

关于swift - NSInvalidArgumentException - 'Invalid top-level type in JSON write' - swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40911333/

相关文章:

ios - textFieldShouldBeginEditing 在所有文本字段上触发

ios - JSON序列化歌曲信息

Python tkinter - 成功从顶层继承

android - 意外的顶级异常 :

python-3.x - Tkinter 模态窗口不允许主窗口最大化

swift - 在 Swift 中将数组传递给具有可变数量参数的函数

ios - 如何快速转换包括时区日期?

json - 使用 alamofire 将带有 JSON 对象和查询参数的 POST 请求发送到 REST web 服务

ios - 序列化 JSON 字符串 SBJSON vs NSJSONSerialization vs 其他?

json - 快速错误 : Invalid top-level type in JSON write