簡體   English   中英

沒有與 Swift JSONDecoder 中的鍵 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM