2014-10-06 29 views
0

我剛剛瞭解到NSURLSession。我想發佈POST請求。它需要JSON作爲主體。在swift中使用字典的不同數據類型?

當使用Objective-C我使用NSDictionary,但在迅速I Dictionary只保存1數據類型。在swift中實現這個的另一種方法是什麼?

{ 
    "userID" : "xxxxxxxx", 
    "full_name" : "xxxxxxxxx", 
    "pob" : "xxxxxxxxxx" 
    "dob" : "xxxxxxxxxxx", 
    "status" : 3, 
    "phone_number" : null, 
    "education" : [ 
     { 
      "university" : "xxxxxx", 
      "location": { 
       latitude: "xxxxxxx", 
       longitude: "xxxxxxxx" 
      }, 
      "degree": "xxxxxx" 
     }, 
     { 
      "university" : "xxxxxx", 
      "location": { 
       latitude: "xxxxxxx", 
       longitude: "xxxxxxxx" 
      }, 
      "degree": "xxxxxx" 
     } 
    ] 
} 

我真的卡住了,我已經找了好幾個小時,但沒有運氣的解決方案。在google中沒有找到關於此的任何教程。

非常感謝你,對不起我的英文不好。

回答

1

只要使用Dictionary<Any, Any>,它就像NSDictionary的

+0

我不能使用任何的鍵,它顯示了一個錯誤「類型‘的任何’不符合協議‘哈希的’」 – taylorSWIFT 2014-10-06 14:20:44

+0

無需使用任何作爲關鍵。它總是一個字符串。 – 2014-10-06 15:29:54

+0

按@HotLicks建議。或者你可以使用'Dictionary ' – Teejay 2014-10-06 15:32:22

1

,您仍然可以使用NSDictionary

var dictionary: NSDictionary = [ 
    "userID" : "xxxxxxxx", 
    "full_name" : "xxxxxxxxx", 
    "pob" : "xxxxxxxxxx", 
    "dob" : "xxxxxxxxxxx", 
    "status" : 3, 
    "phone_number" : NSNull(), 
    "education" : [ 
     [ 
      "university" : "xxxxxx", 
      "location": [ 
       "latitude" : "xxxxxxx", 
       "longitude" : "xxxxxxxx" 
      ], 
      "degree": "xxxxxx" 
     ], 
     [ 
      "university" : "xxxxxx", 
      "location": [ 
       "latitude": "xxxxxxx", 
       "longitude": "xxxxxxxx" 
      ], 
      "degree": "xxxxxx" 
     ] 
    ] 
] 

爲了方便和JSON響應,則可以使用庫,例如​​:

+0

**我會阻止使用老的Obj-C類**。無論如何,+1圖書館。 – Teejay 2014-10-06 13:24:45

+0

同意,但雖然沒有建立在「NSJSONSerialization」的替代方案中,但我認爲仍然有用於「NSDictonary」。 – Kirsteins 2014-10-06 13:30:51

+0

當在swift中使用時,返回一個'NSDictionary'的Obj-C方法返回一個Swift的'Dictionary '。對於返回NSArray的方法也是如此。 – Teejay 2014-10-06 13:56:50

0

嘗試這樣的: -

var dictionary = Dictionary<String, Any> 
dictionary["userID"] = "xxxxxxxx" 
dictionary["status"] = 200 
like that ... 
+0

我試過了。 NSJSONSerialization.dataWithJSONObject(字典,選項:無,錯誤:無) 它的錯誤「類型‘字典’不符合協議‘AnyObject’ – taylorSWIFT 2014-10-06 14:21:33

+0

請參閱更新一個 – 2014-10-06 15:07:10

相關問題