簡體   English   中英

為Alamofire參數創建復雜的[String:AnyObject]

[英]Create complex [String:AnyObject] for Alamofire parameters

這是我與Swift合作的第一個項目,請耐心等待。 我正在嘗試使用Alamofire集成我的REST服務。 在復雜的JSON結構的情況下,構建參數字段會遇到一些麻煩。

服務器需要這樣的結構:

{
  "event": {
    "name": "string",
    "duration": 1,
    "lat": 45.0,
    "lon": 45.0,
    "deadline": "2015-12-01T10:07:14.017Z"
  },
  "proposals": [
    "2015-11-01T10:07:14.017Z"
  ],
  "invitations": [
    {
      "user": 0,
      "phone": "string",
      "email": "string"
    }
  ]
}

建議是NSDate數組,邀請是Dictionary數組,長度都是可變的。

目前,我正在嘗試創建一個NSMutableDictionary ,用必要的字段填充它,最后將其轉換為[String: AnyObject]

這是事件和投標字段的示例:

var parameters: [String:AnyObject] = [
"event" : "",
"proposals": "",
"invitations": "",
]

if let event = mutableParameters.objectForKey("event") as? [String:AnyObject] {
parameters.updateValue(event, forKey: "event")
}

if let prop = mutableParameters.objectForKey("proposals") as? [String:AnyObject] {
parameters.updateValue(prop, forKey: "proposals")
}

但是第二個if不會進入true分支。

有什么建議么? 如果有人有更好的解決方案,這將是公認的!

錯誤是您將mutableParameters.objectForKey("proposals")[String:AnyObject]字典,但這應該是[String] ,它是一個字符串數組:

if let prop = mutableParameters.objectForKey("proposals") as? [String] {
    parameters.updateValue(prop, forKey: "proposals")
}

更新

最好只制作一個Swift字典並使用NSJSONSerialization

let source: [String:AnyObject] = ["event" : ["name": "welcome", "duration": "1", "lat": 45.0,"lon": 45.0,"deadline": "2015-12-01T10:07:14.017Z"], "proposals": ["2015-12-01T10:07:14.017Z"], "invitations": [["user": "eric", "phone": "555", "email": "none"]]]

do {
    let dictionaryAsJSONData = try NSJSONSerialization.dataWithJSONObject(source, options: [])
    // send it to your server, or...
    if let jsonDataAsString = NSString(data: dictionaryAsJSONData, encoding: NSUTF8StringEncoding) {
        // send this
        print(jsonDataAsString)
    }
} catch {
    print(error)
}

這里jsonDataAsString是:

{“ proposals”:[“ 2015-12-01T10:07:14.017Z”],“ invitations”:[{“ email”:“ none”,“ user”:“ eric”,“ phone”:“ 555”} ],“ event”:{“ lon”:45,“ deadline”:“ 2015-12-01T10:07:14.017Z”,“ duration”:“ 1”,“ lat”:45,“ name”:“ welcome “}}

典型的JSON處理比較混亂

您可以使用SwiftyJSON輕松實現此目標

通過Cocoapods或手動安裝。 對於手動,您只需在工作區中下載SwiftyJSON.xcodeproj文件並將其添加。

在構建階段為iOS添加SwiftyJSON框架

在此處輸入圖片說明

現在只需將其導入您的ViewController

import SwiftyJSON

即使在導入后,如果Xcode無法識別它,請清理並構建它。

 let dic1 = ["name": "string", "duration": "1", "lat": 45.0,"lon": 45.0,"deadline": "2015-12-01T10:07:14.017Z"]
 let dic2 = ["2015-12-01T10:07:14.017Z"]
 let dic3 = [["user": "string", "phone": "1", "email": "asd"]]

 let response = [ "event" : dic1,"proposals": dic2,"invitations": dic3]
 print(JSON(response))

輸出量

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM