![](/img/trans.png)
[英]Swift Error: keyNotFound No value associated with key CodingKeys
[英]No value associated with key CodingKeys in Swift JSONDecoder
我正在嘗試解析以下響應
{
"PaymentInfoList": [
{
AccessTokens": [
{
"AccessToken": "d35c9c5d-60d3-7ea2-62f9-6754ed216d9f"
}
],
"CloverPayment": true,
"SquarePayment": false,
}
]
}
模型
struct PaymentInfoList: Codable {
let SquarePayment : Bool
let CloverPayment : Bool
}
網絡服務
func fetchPaymentInfo(Id: String, completion:@escaping(PaymentInfoList)-> ()) {
// Webservice URL & body
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let parseResult = try! JSONDecoder().decode(PaymentInfoList.self, from: data)
DispatchQueue.main.async {
completion(parseResult)
}
} catch {
print(error)
}
}
}.resume()
}
錯誤:
我不明白我哪里出錯了。 請指導
請不要接受答案,添加評論會太長,因此將其添加到此處,將很快刪除
使用以下結構
struct Response: Codable {
let paymentInfoList: [PaymentInfoList]
enum CodingKeys: String, CodingKey {
case paymentInfoList = "PaymentInfoList"
}
}
struct PaymentInfoList: Codable {
let cloverPayment, squarePayment: Bool
enum CodingKeys: String, CodingKey {
case cloverPayment = "CloverPayment"
case squarePayment = "SquarePayment"
}
}
最后將JSONDecoder
語句更改為
let parseResult = try JSONDecoder().decode(Response.self, from: data)
你也可以改變
DispatchQueue.main.async {
completion(parseResult.paymentInfoList)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.