2014-10-06 153 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