簡體   English   中英

通過 Alamofire POST 發送 JSON 或 SwiftyJSON

[英]Sending JSON or SwiftyJSON through Alamofire POST

與此類似的問題之前已發布,但略有不同,即:

Alamofire:發送 JSON 作為請求參數

在 Alamofire POST 方法中發布多個 json 對象 - Swift/IOS

通過 Alamofire 發送 json 陣列

作為最后一個,最接近我當前的問題。 但是,這個解決方案對我不起作用。

我面臨的問題是我正在嘗試通過 Alamofire POST 請求發送一個我使用 SwiftyJSON 構建的 JSON。 像這樣:

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)
                        }
                }

但是,這並不能很好地工作,因為我正在與之通信的 API 似乎不能很好地識別我正在發送的參數。

但后來我注意到我發送的不是有效的 JSON。 這就是我要發送的內容:

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

但在使用將我的 JSON 轉換為 object 之前

let params = [ json.object ]

這是一個通過 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
}

所以問題是我被迫更改 JSON 的結構,因為它似乎是通過 Alamofire 發送它的唯一方法,將其轉換為 object。 有沒有辦法通過 Alamofire 實際發送原始 JSON ?

嘗試為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

嘗試將您的參數作為 Alamofire 參數,即 [String: Any]。

基本上你想用 post 方法發送原始 json 。

function 下面將使用原始 json 進行發布請求。 這也是 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