所以我想发送这样的参数:
我有一个这样的模型:
class test{
var id: String?
var name: String?
}
我希望Json:
[
{
"id":"1",
"name":"asda"
},
{
"id":"2",
"name":"asda"
}
]
以及如何将该类作为参数发送到alamofire ???
让参数:[AnyObject] = listTest但它不起作用:(
任何建议都将不胜感激!
答案 0 :(得分:0)
要使用Alamofire将单个JSON对象发送到您的服务器,您只需将对象转换为可序列化的字典。例如:
extension Test {
func toDict() -> [String: String] {
return ["id": id ?? "", "name": name ?? ""]
}
}
并发送它指定正确的JSON编码:
let parameters = test.toDict()
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default)
发送一个字典数组而不是字典有点棘手。从this answer提取的代码:
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let values = tests.map { $0.toDict() }
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(values, options: [])
Alamofire.request(request)