正如在帖子的標題中提到的,當我嘗試將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