如帖子标题中所述,我在尝试快速将字典转换为 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/