无法使用JSON解码器解析JSON

时间:2018-03-30 05:24:47

标签: ios swift ccavenue

我是swift的新手,我正在尝试整合CCAvenue支付网关。我正在点击服务器从CCAvenue服务器获取支付选项列表,我在响应中获取但是我无法将数据解析为JSON对象,它会抛出一些异常。在此先感谢您的帮助

这是我的代码

override func viewDidLoad() {
        super.viewDidLoad()

let urlAsString = "https://test.ccavenue.com/transaction/transaction.do?"

        let myRequestString = "command=\(COMMAND)&currency=\(currency)&amount=\(amount)&access_code=\(accessCode)&customer_identifier=\(customerIdentifier)"
        let myRequestData = NSData.init(bytes: myRequestString.cString(using: .utf8), length: myRequestString.count) as Data
        let request = NSMutableURLRequest.init(url: URL(string: urlAsString)!)
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type")
        request.setValue(urlAsString, forHTTPHeaderField: "Referer")
        request.setValue("Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30", forHTTPHeaderField: "User-Agent")
        request.httpMethod = "POST"
        request.httpBody = myRequestData

        let requestData = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
            let responseData = NSString.init(data: data!, encoding: String.Encoding.ascii.rawValue)

            if error == nil {
                print("\(responseData)")
            }

            // if request is error free then decode the json using json decoder and assigning the values to the array
            guard let data = data  else {return}
            do{
               let a = try JSONDecoder().decode([CCPaymentOption].self, from: data)

                print("\(String(describing: a))")
            }catch {
                print("Error")
            }
            }.resume()

        print("\(requestData)")
    }

这是我在调试器中得到的内容

Optional({"payOptions":[{"payOpt":"OPTCRDC","payOptDesc":"Credit Card","cardsList":"[{\"cardName\":\"Diners Club\",\"cardType\":\"CRDC\",\"payOptType\":\"OPTCRDC\",\"payOptDesc\":\"Credit Card\",\"dataAcceptedAt\":\"CCAvenue\",\"status\":\"ACTI\"},{\"cardName\":\"MasterCard\",\"cardType\":\"CRDC\",\"payOptType\":\"OPTCRDC\",\"payOptDesc\":\"Credit Card\",\"dataAcceptedAt\":\"CCAvenue\",\"status\":\"ACTI\",\"statusMessage\":\"\"},{\"cardName\":\"Visa\",\"cardType\":\"CRDC\",\"payOptType\":\"OPTCRDC\",\"payOptDesc\":\"Credit Card\",\"dataAcceptedAt\":\"CCAvenue\",\"status\":\"ACTI\"}]"},{"payOpt":"OPTDBCRD","payOptDesc":"Debit Card","cardsList":"[{\"cardName\":\"MasterCard Debit Card\",\"cardType\":\"DBCRD\",\"payOptType\":\"OPTDBCRD\",\"payOptDesc\":\"Debit Card\",\"dataAcceptedAt\":\"CCAvenue\",\"status\":\"ACTI\"},{\"cardName\":\"Visa Debit Card\",\"cardType\":\"DBCRD\",\"payOptType\":\"OPTDBCRD\",\"payOptDesc\":\"Debit Card\",\"dataAcceptedAt\":\"CCAvenue\",\"status\":\"ACTI\"}]"},{"payOpt":"OPTNBK","payOptDesc":"Net Banking","cardsList":"[{\"cardName\":\"AvenuesTest\",\"cardType\":\"NBK\",\"payOptType\":\"OPTNBK\",\"payOptDesc\":\"Net Banking\",\"dataAcceptedAt\":\"CCAvenue\",\"status\":\"ACTI\",\"statusMessage\":\"\"}]"}]})

错误

1 个答案:

答案 0 :(得分:1)

解码对象时需要检查许多点。

  1. 确保您的CCPaymentOption模型 addopt 协议可编码
  2. 在解码数据时,请确保您清楚您的回复是词典数组
  3. 假设您正在回复数组,在这种情况下,您可以直接在J SONDecoder()。decode()方法中使用[ CCPaymentOption]
  4. 如果您从服务器响应中获取词典,那么您需要以这种方式解码对象。
  5. 对于点号 3 的CCPaymentOption模型的

    示例

    struct CCPaymentOption : Codable {
        var amount:String  // Note down that , please use exact same 
                           // key as you are getting from server side.
    }
    
    do {
    
           let arrPaymentOptions = try JSONDecoder().decode([CCPaymentOption].self, from: responseData)
    
                   print(arrPaymentOptions)
                   ///... Array of Your Model reference.
    
        } catch {
                   print(error)
                }
    
    对于点号 4 的CCPaymentOption模型的

    示例

    struct CCPaymentOption : Codable {
        var amount:String
    }
    
    struct responseDictionary : Codable {
        var paymentOption:[CCPaymentOption] // Note down that , please 
                                            // use exact same key as you 
                                            // are getting from server 
                                            // side.
    }
    
    do {
    
            let responseDict = try JSONDecoder().decode(responseDictionary.self, from: responseData)
    
                   print(responseDict.paymentOption)
                   // responseDict.paymentOption is the Array of Your 
                   // Model reference.
    
        } catch {
                   print(error)
                }
    

    如果您不想使用JSON解码器,请尝试以下一项。 : -

    URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
    
                        guard error == nil else { return }
                        guard let responseData = data else { return }
    
                        do {
    
                            if let jsonObject = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String:Any] {
                                ///... All you want is here  jsonObject is the Dictionary (required , not an optional)  
                            }
    
                        } catch  {
                            print(error)
                        }
                    }).resume()
    

    从服务器端获取数据后,您需要在本机方法的帮助下执行 JSONSerialization 。此方法将返回 字典数组服务器上的取决于 响应即可。)