无法转换类型&#39; Swift.Dictionary的值<swift.string,protocol <=“”>&gt;&#39;到了Swift.AnyObject&#39;

时间:2016-11-04 05:35:40

标签: json swift dictionary swift2

我正在尝试将[String : Any]转换为JSON格式,然后再将其发送到API。

var orderRequestUserValues : [String : Any]   = [ "ClientID": "\(clientID)",
                                                       "UserName": "\(userName)",
                                                       "Password": "\(password)",
                                                       "ModuleID": "StockProcessing",
                                                       "FunctionID": "SetStockOrder",
                                                       "TransmissionFlags": 32,
                                                       "TransmissionMethod": 5


    ]

var requestParameters : [String : Any] = [  "ActivityType": 2,
                                            "ActivityReference1": "",
                                            "ActivityReference2": "",
                                            "Notes": "",
                                            "ProcessingUserUnique": 1
                                            ]

requestParameters.updateValue(usedObjectDictionaries, forKey: "ListofStockActivityData")


orderRequestUserValues.updateValue(requestParameters, forKey: "RequestParameters")

但是因为我的投射方法需要AnyObject我尝试并强制施放它,但是我收到错误:

  

无法转换类型&#39; Swift.Dictionary&gt;&#39;到了Swift.AnyObject&#39;。

do{

   let newDict = try NSJSONSerialization.dataWithJSONObject(orderRequestUserValues as! AnyObject, options: NSJSONWritingOptions.PrettyPrinted)  // Inflicts an error

   let decoded = try NSJSONSerialization.JSONObjectWithData(newDict, options: [])

我必须使用另一种方法来转换为JSON格式,或者什么是我最好的选择。

3 个答案:

答案 0 :(得分:2)

[String : Any](a.k.a。Dictionary<String, Any>)是一个结构,而不是一个对象。因此,它无法转换为AnyObject

但是,Dictionary(明确地)通过强制转换为NSDictionary

 let newDict = try NSJSONSerialization.dataWithJSONObject(orderRequestUserValues as NSDictionary, options: NSJSONWritingOptions.PrettyPrinted)

答案 1 :(得分:2)

您正在使用Swift 2,而您遇到的问题是Any无法转换为AnyObject。从AnyAnyObject进行向下投射是不可能的。因此,请将您的字典声明为[String: AnyObject],而不是[String: Any]

var orderRequestUserValues : [String : AnyObject]   = [ "ClientID": "\(clientID)",
                                                   "UserName": "\(userName)",
                                                   "Password": "\(password)",
                                                   "ModuleID": "StockProcessing",
                                                   "FunctionID": "SetStockOrder",
                                                   "TransmissionFlags": 32,
                                                   "TransmissionMethod": 5]

答案 2 :(得分:0)

在Swift 3中,这种方式对我来说工作得很好。

let mutableDict = NSMutableDictionary(dictionary:newDictionaryResult!)