我正在尝试从服务器读取人类可读格式的响应错误。我知道这里有一个错误,我只是不知道如何解析JSON。我收到错误消息由于格式不正确而无法读取数据。
这是我正在尝试的:
var request = URLRequest(url:url)
request.httpBody = "stripeToken=\(token.tokenId)&amount=\(priceInt)".data(using: String.Encoding.utf8)
request.httpMethod = "POST"
URLSession.shared.dataTask(with: request) { (data, response, error) -> Void in
// TODO: Handle success or failure
if let data = data {
do {
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print("Json: \(json)")
}
} catch {
print("Catch Error: \(error.localizedDescription)")
}
响应正文:
{
"error": {
"charge": "ch_1E5yhbAtWFyXMp9t5rTIyGwM",
"code": "card_declined",
"decline_code": "generic_decline",
"doc_url": "https://stripe.com/docs/error-codes/card-declined",
"message": "Your card was declined.",
"type": "card_error"
}
}