【发布时间】:2019-11-19 11:18:14
【问题描述】:
这样的json发布响应:
{
"response": {
"responseReason": "Successful",
"billDetails": "",
"billerResponse":"{\"customerName\":\"RAM\",\"amount\":193,\"dueDate\":\"2019-11-30\",\"custConvFee\":\"\",\"custConvDesc\":\"\",\"billDate\":\"2019-11-16\",\"billNumber\":\"32224081911191623\",\"billPeriod\":\"NA\",\"billTags\":[],\"fieldName\":\"Service Number\",\"fieldValue\":\"116515M025007621\",\"billerName\":\"EPDCL-Eastern Power Distribution Ltd\"}",
为此,我编写了如下代码:
在这里我得到 json 响应,但我需要标签中的 customerName amount dueDate 值
func billerFetchService(){
let parameters = ["billDetails": [
"billerId" : "EPDCLOB00ANP01",
"customerParams" : [["name":"Service Number","value":"116515M025007621"]]]]
let url = URL(string: "https://app.com/fetch_v1/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)")
let billerDetails = json["billerResponse"] as! String
print("fetch only billerdetails \(billerDetails)")
let res = try JSONSerialization.jsonObject(with:Data(billerDetails.utf8)) as! [String: Any]
let billerName = res["customerName"] as? String
print("fetch only EPDCL biller name \(billerName)"
}catch{
print("error")
}
}
}).resume()
}
let billerDetails = json["billerResponse"] as! String我来了
线程 5:致命错误:在展开可选值时意外发现 nil
【问题讨论】:
标签: json swift string dictionary post