我正在使用iOS应用程序并在其中使用swift。我正在调用Rest api,响应是JSON。
这是我的代码:
{
let request = NSMutableURLRequest(url: NSURL(string: path)! as URL)
// Set the method to POST
request.httpMethod = "POST"
do {
// Set the POST body for the request
let jsonBody = try JSONSerialization.data(withJSONObject: body, options: .prettyPrinted)
request.httpBody = jsonBody
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
// request.addValue("Cookie", forHTTPHeaderField: session_Id)
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
if let jsonData = data {
print("\(data?.debugDescription)")
do {
print("JSON Response String: \(String.init(data: data!, encoding: .utf8))")
let dict:[String:Any] = (try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String:Any])!
print("JSON Response Dictionary: \(dict)")
onCompletion(dict, nil)
} catch {
// report ERROR
print("caught: \(error)")
onCompletion(nil, error as! NSError)
}
} else {
print(error)
onCompletion(nil, error as! NSError)
}
})
task.resume()
} catch {
// Create your personal error
onCompletion(nil, nil)
}
}
这是api的响应:
======== - Fetch CC list api request - =============
["userID": "898465844"]
======== - Fetch CC list api request - =============
JSON Response String: "{\"status\":\"success\",\"card_list\":[{\"cardType\":\"Visa\",\"cardholderName\":null,\"expirationMonth\":\"01\",\"expirationYear\":\"2020\",\"cardImage\":\"https://assets.braintreegateway.com/payment_method_logo/visa.png?environment=sandbox\",\"cardNumber\":\"411111******1111\",\"token\":\"348nws\"}]}"
JSON Response Dictionary: ["status": success, "card_list": <__NSSingleObjectArrayI 0x1c060f350>(
{
cardImage = "https://assets.braintreegateway.com/payment_method_logo/visa.png?environment=sandbox";
cardNumber = "411111******1111";
cardType = Visa;
cardholderName = "<null>";
expirationMonth = 01;
expirationYear = 2020;
token = 348nws;
}
)
]
解析后,我在字典的“ card_list”数组中的“:”处得到了“ =”。
因此,我无法弄清为什么在“:”处出现“ =”的原因。
答案 0 :(得分:0)
您的回复格式看起来不像JSON。它的属性列表或(XML)尝试使用-PropertyListSerialization.propertyList(from:...)
或某些XML解析器