从服务器获取JSON响应数据

时间:2019-02-20 18:18:22

标签: json swift httprequest httpresponse

我正在尝试从服务器读取人类可读格式的响应错误。我知道这里有一个错误,我只是不知道如何解析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"
  }
}

0 个答案:

没有答案
相关问题