我想在单个请求中发送多个不同的JSON对象,我觉得在单个请求中像文件一样流式传输多个JSON对象会更好,所以请告诉我是否可行,如果可以的话请给我一个思路要使用Alamofire做到这一点,下面是我要发布的原始正文(应用程序/ json)数据的格式
{"a":23214,"b":54674,"c":"aa12234","d":4634} {"a":32214,"b":324674,"c":"as344234","d":23434} {"a":567214,"b":89674,"c":"sdf54234","d"34634}
我尝试了下面的代码,但是由于body参数的格式不正确,因此无法正常工作,这就是我想尝试在单个请求中将多个JSON对象作为流发送的原因,请注意
let SendParams = [ ["a":1234, "b":2345, "c":3456], ["a":2345, "b":3456, "c":4567], ["a":3456, "b":4567, "c":5678] ] _ = Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding, headers: header)
JSON格式不适合您的请求,JSON始终是键值对,其中key始终是String,value是any Object。在您的示例中,需要Array为以下类型的对象设置顶级密钥:
String
Object
Array
let SendParams = [ "key" :[["a":1234, "b":2345, "c":3456], ["a":2345, "b":3456, "c":4567], ["a":3456, "b":4567, "c":5678]] ] _ = Alamofire.request(url, method: .post, parameters: SendParams, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in}
要么
连载阵列和作为集httpBody的URLRequest对象:
httpBody
URLRequest
let url = YOUR_POST_API_URL var request = URLRequest(url: URL(string: url)!) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") let values = [ ["a":1234, "b":2345, "c":3456], ["a":2345, "b":3456, "c":4567], ["a":3456, "b":4567, "c":5678] ] request.httpBody = try! JSONSerialization.data(withJSONObject: values) Alamofire.request(request) .responseJSON { response in // do whatever you want here switch response.result { case .failure(let error): print(error) if let data = response.data, let responseString = String(data: data, encoding: .utf8) { print(responseString) } case .success(let responseObject): print(responseObject) } }