简体   繁体   English

通过 Alamofire POST 发送 JSON 或 SwiftyJSON

[英]Sending JSON or SwiftyJSON through Alamofire POST

Similar questions to this have been posted before but with slight differences, namely:与此类似的问题之前已发布,但略有不同,即:

Alamofire: Sending JSON as request parameter Alamofire:发送 JSON 作为请求参数

POST multiple json objects in Alamofire POST method - Swift/IOS 在 Alamofire POST 方法中发布多个 json 对象 - Swift/IOS

Sending json array via Alamofire 通过 Alamofire 发送 json 阵列

being the last one, the closest to my current problem.作为最后一个,最接近我当前的问题。 However, this solution is not working for me.但是,这个解决方案对我不起作用。

The problem I am facing is that I'm trying to send through an Alamofire POST request, a JSON that I've built using SwiftyJSON.我面临的问题是我正在尝试通过 Alamofire POST 请求发送一个我使用 SwiftyJSON 构建的 JSON。 Like so:像这样:

let url = NSURL(string: orderProductsEndpoint)
                let request = NSMutableURLRequest(URL: url!)
                request.HTTPMethod = "POST"
                request.setValue(requestToken, forHTTPHeaderField: "Authorization:")
                request.setValue("application/json", forHTTPHeaderField: "Content-Type")

                let params = [ json.object ]
                print(params)

                request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject( params, options: [])


                Alamofire.request(request)
                    .responseString{ response in
                        switch response.result {
                        case .Success(let value):
                            print("gut")
                            print(value)
                        case .Failure(let error):
                            print("not gut")
                            print(error)
                        }
                }

However, this is not working well because the API that I'm communicating with doesn't seem to recognize well the parameters that I'm sending.但是,这并不能很好地工作,因为我正在与之通信的 API 似乎不能很好地识别我正在发送的参数。

But then I noticed that what I am sending is not a valid JSON.但后来我注意到我发送的不是有效的 JSON。 This is what I am sending:这就是我要发送的内容:

  [{
car =     (
            {
        cant = 2;
        id = 6;
        name = "Saudi Plate";
    },
            {
        cant = 1;
        id = 5;
        name = "Beef Wrap";
    }
);
idUser = 58;
"total_loyalty_points" = 4200;
"total_price" = 42000;}]

But before converting my JSON to an object using但在使用将我的 JSON 转换为 object 之前

let params = [ json.object ]

It was a valid JSON validated through JSONLint and it looks like this这是一个通过 JSONLint 验证的有效 JSON,它看起来像这样

{
  "total_price" : 42000,
  "car" : [
    {
      "id" : "6",
      "cant" : 2,
      "name" : "Saudi Plate"
    },
    {
      "id" : "5",
      "cant" : 1,
      "name" : "Beef Wrap"
    }
  ],
  "idUser" : 58,
  "total_loyalty_points" : 4200
}

So the problem is that I was forced to change the structure of the JSON because it seems to be the only way to send it through Alamofire, by converting it into an object.所以问题是我被迫更改 JSON 的结构,因为它似乎是通过 Alamofire 发送它的唯一方法,将其转换为 object。 Is there a way to actually send raw JSON through Alamofire?有没有办法通过 Alamofire 实际发送原始 JSON ?

Try setting the json encoding for your parameters in the Alamofire request. 尝试为Alamofire请求中的参数设置json编码。

Alamofire.request("http://...", method: HTTPMethod.post, parameters: parameters, encoding: JSONEncoding.default, headers: nil)
         .responseJSON(completionHandler: {(response) in ... })

https://github.com/Alamofire/Alamofire#json-encoding https://github.com/Alamofire/Alamofire#json-encoding

Try to get your params as Alamofire parameters ie [String: Any].尝试将您的参数作为 Alamofire 参数,即 [String: Any]。

Basically you want to send raw json with post method.基本上你想用 post 方法发送原始 json 。

Below function will do a post request with raw json. function 下面将使用原始 json 进行发布请求。 Also this is with generics这也是 generics

func nwCallRawJSon<T: Decodable>(url : String, param : [String : Any],decodable: T.Type,onCompletion: @escaping (T?,Error?) -> Void){
        AF.request(url, method: .post, parameters : param, encoding: JSONEncoding.default, headers: nil).validate(contentType: ["application/json"]).responseDecodable { (response: DataResponse<T,AFError>) in
            switch response.result {
            case .success(let data):
                onCompletion(data,nil)
            case .failure(let error):
                onCompletion(nil,error)
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM