正如在帖子的标题中提到的,当我尝试将Dictionary转换为JSON数据时,我得到NSInvalidArgumentException - 'JSON写入中的无效顶级类型' swiftNSInvalidArgumentException - '无效的JSON写入的顶级类型' - 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
}
}
我传递字典作为参数,没有得到什么问题。请帮助我们。
谢谢!
func jsonEncode(object: Any) -> Data? {
return try? JSONSerialization.data(withJSONObject: object, options:[])
}
如果你真的需要传递一个可选的,那么你必须解开它:
为什么在这行的末尾添加'as Data?'? – Moritz
另外,您将'Any?'传递给'JSONSerialization.data(withJSONObject:)',但它应该先安全地解包。 – Moritz
哦! '作为数据?'错误...我是新来的迅速。所以请告诉我应该做些什么。谢谢指出 – iAkki