如何使用SwiftyJSON解析具有AnyHashable值的PayPal JSON响应?

时间:2017-02-27 21:43:57

标签: json swift swifty-json paypal hashable

我正在使用PaypalSDK将paypal支付方式添加到我正在开发的应用程序中,它已经正常工作,当付款成功时,我得到一个响应,我正在转换为jsonObject但我不知道如何解析它以便仅从响应中提取代码。这是我得到的回应

JSON: [AnyHashable("response"): {
code = "******************* -****************-**********************";
}, AnyHashable("response_type"): authorization_code, AnyHashable("client"): {
environment = sandbox;
"paypal_sdk_version" = "2.11.5";
platform = iOS;
"product_name" = "PayPal iOS SDK";
}]

这就是我在payPalFuturePaymentViewController方法上的内容:

  func payPalFuturePaymentViewController(_ futurePaymentViewController: PayPalFuturePaymentViewController, didAuthorizeFuturePayment futurePaymentAuthorization: [AnyHashable: Any]) {
    print("PayPal Future Payment Authorization Success!")
    self.resultText = futurePaymentAuthorization.description
    let jsonObject = JSON(futurePaymentAuthorization.description)
    print("JSON: \(jsonObject)")
    // send authorization to your server to get refresh token.
    futurePaymentViewController.dismiss(animated: true, completion: { () -> Void in

        var paypalPago = PagoItem(noTarjeta: "", fechaExp: "", cvc: "", token: "", tipo: "PayPal")

        self.metodosPago.append(paypalPago)
        self.saveMetodo()

        let destViewController : UIViewController = self.storyboard!.instantiateViewController(withIdentifier: "pagosLlenos")
        var vcArray = self.navigationController?.viewControllers

        vcArray?.removeLast()
        vcArray?.append(destViewController)
        self.navigationController?.setViewControllers(vcArray!, animated: true)
    })
}

所以我想做的是从响应中获取代码,将其放在变量中,然后在paypalPago项中包含该变量:

 var paypalPago = PagoItem(noTarjeta: "", fechaExp: "", cvc: "", token: PayPalCode, tipo: "PayPal")

如何解析这个json并提取我需要的代码的任何帮助将非常感激:)

1 个答案:

答案 0 :(得分:1)

<强>解决

实际上问题很简单,我存储字符串描述而不是实际的JSON响应,所以我不得不改变

let jsonObject = JSON(futurePaymentAuthorization.description)

let jsonObject = JSON(futurePaymentAuthorization)

现在我的回答如下:

JSON: {
"client" : {
"environment" : "sandbox",
"product_name" : "PayPal iOS SDK",
"paypal_sdk_version" : "2.11.5",
"platform" : "iOS"
  },
"response_type" : "authorization_code",
"response" : {
"code" : "****************_*********_***********************"
 }

现在我可以像任何普通的JSON那样解析它

    let response = jsonObject["response"]["code"].string!
    print(response)

    // send authorization to your server to get refresh token.
    futurePaymentViewController.dismiss(animated: true, completion: { () -> Void in
        var paypalPago = PagoItem(noTarjeta: "", fechaExp: "", cvc: "", token: response, tipo: "PayPal")
    self.metodosPago.append(paypalPago)