如何在Swift中使用Alamofire将发送数组的字典(JSON格式)发送到服务器3

我试图创build和发送字典JSON格式的数组Alamofire。

{ "attendance": [{ "attndid":"0", "psngrtype": "student", "date":currentdate, "cuid": "25", "enttid": "21", }] } 

在这里,我使用了tableview,在上面的“cuid”&“enttid”中我给出了可选的tableview单元格数据的值。 剩下的是不变的。 我传递一个字典数组,如果我select一个tableview单元格数据。 和两个数组,如果我select两个cells.etc ..和我使用下面的代码,我得到但得到问题创build字典格式。 我的代码:

  let arrayOfDictionaries: [[String:AnyObject]] = [ ["psngrtype":"student" as AnyObject, "attndid": "0" as AnyObject , "cuid":stdpasngerid as AnyObject, "enttid": entitID as AnyObject, "attnddate":CurrentDate as AnyObject ]] print(arrayOfDictionaries.toJSONString()) extension Collection where Iterator.Element == [String:AnyObject] { func toJSONString(options: JSONSerialization.WritingOptions = .prettyPrinted) -> String { if let arr = self as? [[String:AnyObject]], let dat = try? JSONSerialization.data(withJSONObject: arr, options: options), let str = String(data: dat, encoding: String.Encoding.utf8) { return str } return "[]" } } 

输出:

 [{ "enttid" : "1", "psngrtype" : "student", "attnddate" : "10-26-2017", "attndid" : "0", "cuid" : "25" }] 

我想添加第一个像json format.and添加多个数组,如果我select多个tableview单元格。 请帮我卡住了?

只要你能做到

 var finalArray:[String:String] = [:] finalArray["Attandance"] = arrayOfDictionaries.toJSONString() 

对象映射,你可以使用ObjectMapper库。

创build对象类似于

 class Attendance: Mappble { var objects: [AttendancesAttributes] = [] init () { } required init?(map:Map) { } func mapping(map: Map){ objects <- map["attendance"] } } 

然后创build您的AttendancesAttributes对象

 class AttendancesAttributes: Mappable { var id: String .... func mapping(map: Map) { //do the mapping with your dictionary } } 

然后在你的VC我猜你可以做

 var attendance: Attendance = Attendance() func (_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //check if your object is or not in your array. attendance.objects.append(yourTableViewFeeder[indexPath.row]) } 

最后在你的API客户端中:

  func sendAttendanceInformationsToServer(attendance: Attendance) { Alamofire.request(url, method, parameters: attendance.toJSON(), encoding: JSONEncoding.default, headers: ["":""]).responseJSON (completionHandler: { //deal your response here }) }