首页 > 解决方案 > 如何在快速解析时在参数中添加post api请求

问题描述

这是我的 api 请求:

{
"billDetails": {
           "billerId":"EPDCLOB00AN232",
            "customerParams":[{"name":"Service Number","value":"116515M025033"}]
             }
}

这是代码:

func billerFetchService(){

let parameters = ["billDetails": {
    "billerId" : "EPDCLOB00ANP01",
    "customerParams" : [{"name":"Service Number","value":"116515M025007621"}]
                                 }
                  ] as [String : Any]


let url = URL(string: "https://app.com/Fetch/fetch")
var req =  URLRequest(url: url!)
req.httpMethod = "POST"
req.addValue("application/json", forHTTPHeaderField: "Contet-Type")
req.addValue("application/json", forHTTPHeaderField: "Accept")

guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) else {return}
req.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: req, completionHandler: {(data, response, error) in
    if response != nil {
        // print(response)
    }
    if let data = data {
        do{
            var json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: Any]
            print("fetching json \(json)")

        }catch{
            print("error")
        }
    }
}).resume()
}

如果我这样添加parameters错误

一行中的连续语句必须用';'分隔
插入 ';' 预期表达

我在哪里做错了,请在代码中帮助我

标签: iosjsonswiftpostparameter-passing

解决方案


请把你的参数设置成这样

 let parameters = ["billDetails":
         [
          "billerId": "EPDCLOB00ANP01",
         "customerParams" : ["name":"Service Number","value":"116515M025007621"]
        ]
        ] as [String : Any]

推荐阅读