我的同事后端程序员说他已经配置了一个 API,希望从我的移动应用程序接收类似的内容:
[{"id":50},{"id":60}]
我正在使用 Alamofire,它接收要发送的参数字典。但我相信这也是使用 NSURLSession 或任何其他第三方插件的相同机制。
问题是:我应该如何构造字典来发送 id 数组,就像 HTTP 表单如何可以有多个具有相同 id 的文本字段,然后它将作为 id 数组在服务器端接收?到目前为止我已经尝试过但都失败了:
param.setValue(50, forKey:"id");
param.setValue(60, forKey:"id");
// this only send the last single value
param.setValue([50, 60], forKey:"id");
// this results in error (415 unsupported media type)
param.setValue(50, forKey:"id[0]");
param.setValue(60, forKey:"id[1]");
// this also results in error (415 unsupported media type)
如何像网络表单发送一样正确发送此信息?谢谢。
最佳答案
我认为您问题的关键字是“Alamofire send json”
如果你的服务器接受json数据,你可以这样做:
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let values = [["id":50],["id":60]]
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(values, options: [])
Alamofire.request(request)
.responseJSON { response in
// do whatever you want here
}
祝你好运!
关于arrays - 如何使用 JSON 发送带有数组的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37669959/