[英]Send JSON with array of objects as parameter in Alamofire with swift
[英]How Can I make & send array of dictionary (JSON Format ) send to server using Alamofire in swift 3
我嘗試創建字典JSON格式的數組並將其發送到Alamofire。
{
"attendance": [{
"attndid":"0",
"psngrtype": "student",
"date":currentdate,
"cuid": "25",
"enttid": "21",
}] }
在這里,我使用了tableview,在上面的“ cuid”和“ enttid”中,我從可選tableview單元格數據中給出了值。 其余的都是常數。 如果我選擇一個tableview單元格數據,則傳遞一個字典數組。 和兩個數組,如果我選擇兩個單元格等。我正在使用下面的代碼,但得到的問題是創建字典格式。 我的代碼:
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格式。如果我選擇多個tableview單元,則添加多個數組。 請幫我卡住嗎?
只需您即可
var finalArray:[String:String] = [:]
finalArray["Attandance"] = arrayOfDictionaries.toJSONString()
對象映射,可以使用ObjectMapper庫。
創建像這樣的對象出勤
class Attendance: Mappble {
var objects: [AttendancesAttributes] = []
init () { }
required init?(map:Map) { }
func mapping(map: Map){
objects <- map["attendance"]
}
}
然后創建您的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
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.