这是我的班级模特
class OrderModel {
var mId:String?
var productCode:String?
var orderQty : Int?
var productRate : Int?
var requiredOn : String?
var orderAddress:String?
var remarks:String?
var productTtitle : String?
var orderAmount:Int?
var branchId:String?
}
我想发送像
这样的JSON{
"order_model":[
{
"m_id": "121212",
"Product_code": "000001",
"Order_qty": 2,
"Product_rate": 100,
"Order_amount" : 200,
"Required_on": "2018-02-01T12:32:33.8550337+05:00",
"branch_id" : "1701001",
"Order_Address": "address",
"Remarks": "rem"
}, {
"m_id": "12234334",
"Product_code": "000002",
"Order_qty": 1,
"Product_rate": 100,
"Order_amount" : 100,
"Required_on": "2018-02-01T12:32:33.8550337+05:00",
"branch_id" : "1701001",
"Order_Address": "address",
"Remarks": "rem"
}
]
}
关于这个主题有很多方法,但我没有解决我的问题并尝试了所有这些方法。我没有得到关于如何将MyCalss模型列表转换为指定JSON的解决方案
这是我的代码
var prams: [String: Any] = [:]
var prodArray:[NSMutableDictionary] = [NSMutableDictionary()]
for product in OrderSingleton.sharedInstance.orderModelList
{
let prod: NSMutableDictionary = NSMutableDictionary()
prod.setValue(product.mId, forKey: "m_id")
prod.setValue(product.productCode, forKey: "Product_code")
prod.setValue(product.orderQty, forKey: "Order_qty")
prod.setValue(product.productRate, forKey: "Product_rate")
prod.setValue(product.orderAmount, forKey: "Order_amount")
prod.setValue(product.requiredOn, forKey: "Required_on")
prod.setValue(product.branchId, forKey: "branch_id")
prod.setValue(product.orderAddress, forKey: "Order_Address")
prod.setValue(product.remarks, forKey: "Remarks")
prodArray.append(prod)
}
prams["order_model"] = prodArray
var request = URLRequest(url: try! urlString.asURL())
request.httpMethod = "POST"
let values = prams
print(values)
request.httpBody = try! JSONSerialization.data(withJSONObject: values)
Alamofire.request(request).responseData { response in
switch (response.result) {
case .success:
let json = response.result.value
let jsonString = String(data: json!, encoding: String.Encoding.utf8)
print("JSON String " , jsonString!)
case .failure(let error):
print ("error ",error)
}
}
我上面代码的输出是
["order_model": [{
"Order_Address" = 923218565452;
"Order_amount" = 1;
"Order_qty" = 1;
"Product_code" = 000001;
"Product_rate" = 1500;
Remarks = rem;
"Required_on" = "2018-02-01T12:32:33.8550337+05:00";
"branch_id" = 1701001;
"m_id" = 923218565452;
}, {
"Order_Address" = 923218565452;
"Order_amount" = 1;
"Order_qty" = 1;
"Product_code" = 000002;
"Product_rate" = 1500;
Remarks = rem;
"Required_on" = "2018-02-01T12:32:33.8550337+05:00";
"branch_id" = 1701001;
"m_id" = 923218565452;
}]]
这是我试过的代码
答案 0 :(得分:1)
我认为你应该写这样的alamofire请求。 我会帮你的。 快乐编码:)
Alamofire.request(urlString, method: .post, parameters: prams,encoding: JSONEncoding.default, headers: nil).validate().responseData{ response in
switch response.result {
case .success:
break
case .failure( let error):
print(error)
break
}
}
}