2016-10-24 32 views
4

我想我的字典迅速轉換成JSON字符串,但得到奇怪的崩潰:「無效的類型在JSON寫(_SwiftValue)」崩潰:轉換字典JSON字符串在3斯威夫特說</p> <p>終止應用程序由於未捕獲的異常「NSInvalidArgumentException」,原因

我的代碼:

let jsonObject: [String: AnyObject] = [ 
      "firstname": "aaa", 
      "lastname": "sss", 
      "email": "my_email", 
      "nickname": "ddd", 
      "password": "123", 
      "username": "qqq" 
      ] 

do { 
    let jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted) 
    // here "jsonData" is the dictionary encoded in JSON data 

    let decoded = try JSONSerialization.jsonObject(with: jsonData, options: []) 
    // here "decoded" is of type `Any`, decoded from JSON data 

    // you can now cast it with the right type 
    if let dictFromJSON = decoded as? [String:String] { 
     // use dictFromJSON 
    } 
} catch { 
    print(error.localizedDescription) 
} 

請幫幫我!

問候。

+0

「我的代碼」來自https://stackoverflow.com/a/29625483/2227743 – Moritz

回答

17

字符串不是AnyObject。對象是參考類型,但字符串在swift中有值語義。 A 字符串但是,可以是類型任何,所以下面的代碼工作。我建議你閱讀Swift中的引用類型和值語義類型;它是一個微妙但重要的區別,它與大多數其他語言所期望的不同,其中String通常是引用類型(包括目標C)。

let jsonObject: [String: Any] = [ 
     "firstname": "aaa", 
     "lastname": "sss", 
     "email": "my_email", 
     "nickname": "ddd", 
     "password": "123", 
     "username": "qqq" 
    ] 

    do { 
     let jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted) 
     // here "jsonData" is the dictionary encoded in JSON data 

     let decoded = try JSONSerialization.jsonObject(with: jsonData, options: []) 
     // here "decoded" is of type `Any`, decoded from JSON data 

     // you can now cast it with the right type 
     if let dictFromJSON = decoded as? [String:String] { 
      print(dictFromJSON) 
     } 
    } catch { 
     print(error.localizedDescription) 
    } 
+0

謝謝您的幫助。 –

+0

不工作了,嘗試必須以某種方式處理? –

+0

嘗試由catch子句處理 – Moonwalkr

相關問題