如何使用alamofire将多个JSON对象作为流发送

时间:2018-01-29 06:13:53

标签: json xcode alamofire swift4

我想在一个请求中发送多个不同的JSON对象,我觉得像单个请求中的文件一样流式传输多个JSON对象会更好,所以如果可能的话,请让我知道,如果这样请给我一个关于如何使用Alamofire做到这一点的想法,下面是我要发布的原始正文(application / 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}

我尝试了下面的代码,但它没有工作,因为正文格式不是正确的格式,这就是我想尝试在单个请求中将多个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)

1 个答案:

答案 0 :(得分:3)

JSON格式不适合您的请求,JSON始终是键值对,其中键始终为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}

OR

序列化数组并设置为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)
            }
    }