我是swift的新手,我正在尝试整合CCAvenue支付网关。我正在点击服务器从CCAvenue服务器获取支付选项列表,我在响应中获取但是我无法将数据解析为JSON对象,它会抛出一些异常。在此先感谢您的帮助
这是我的代码
override func viewDidLoad() {
super.viewDidLoad()
let urlAsString = "https://test.ccavenue.com/transaction/transaction.do?"
let myRequestString = "command=\(COMMAND)¤cy=\(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\":\"\"}]"}]})
错误
答案 0 :(得分:1)
解码对象时需要检查许多点。
示例。
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 。此方法将返回 字典或数组(服务器上的取决于 响应即可。)