来自JSON响应的Swift数据模型

icomxhvb  于 2022-12-01  发布在  Swift
关注(0)|答案(2)|浏览(148)

我在为以下JSON响应构建正确的数据模型时遇到了问题。

{
  "resources": [
    {
      "courseid": 4803,
      "color": "Blue",
      "teeboxtype": "Championship",
      "slope": 121,
      "rating": 71.4
    },
    {
      "courseid": 4803,
      "color": "White",
      "teeboxtype": "Men's",
      "slope": 120,
      "rating": 69.6
    },
    {
      "courseid": 4803,
      "color": "Red",
      "teeboxtype": "Women's",
      "slope": 118,
      "rating": 71.2
    }
  ]
}

这是当前的模型。无论我做什么,我似乎都无法填充模型。这也是我的URL会话检索数据。我是新的Swift和SwiftUI,所以请温和。我正在得到数据回来,但我错过了一些东西。

import Foundation

struct RatingsResources: Codable {
    let golfcourserating : [GolfCourseRating]?
}
    
    struct GolfCourseRating: Codable {
        let id: UUID = UUID()
        let courseID: Int?
        let teeColor: String?
        let teeboxtype: String?
        let teeslope: Double?
        let teerating: Double?
        
        enum CodingKeysRatings: String, CodingKey {
            case courseID = "courseid"
            case teeColor = "color"
            case teeboxtype
            case teeslope = "slope"
            case teerating = "rating"
        }
    }

    func getCoureRating(courseID: String?) {
       let semaphore = DispatchSemaphore (value: 0)
       
       print("GETTING COURSE TEE RATINGS..........")
       
       let urlString: String = "https://api.golfbert.com/v1/courses/\(courseID ?? "4800")/teeboxes"
       
       print ("API STRING: \(urlString) ")
       
       let url = URLComponents(string: urlString)!
       let request = URLRequest(url: url.url!).signed
       let task = URLSession.shared.dataTask(with: request) { data, response, error in
       let decoder = JSONDecoder()
            
            guard let data = data else {
                print(String(describing: error))
                semaphore.signal()
                return
            }
           
               if let response = try? JSONDecoder().decode([RatingsResources].self, from: data) {
                   DispatchQueue.main.async {
                       self.ratingresources = response
                   }
                   return
               }

           print("*******Data String***********")
           print(String(data: data, encoding: .utf8)!)
           print("***************************")
           
           let ratingsData: RatingsResources = try! decoder.decode(RatingsResources.self, from: data)
           
           print("Resources count \(ratingsData.golfcourserating?.count)")
           
             semaphore.signal()
           }

           task.resume()
           semaphore.wait()
           
   } //: END OF GET COURSE SCORECARD
k0pti3hp

k0pti3hp1#

首先,在解码JSON时,千万不要使用try?。这会隐藏所有错误。使用try和一个合适的do/catch块。在catch块中至少打印error
看看你的模型,这里似乎有三个问题。

  • 你的数组中没有RatingsResources的数组,它只是一个示例。
let response = try JSONDecoder().decode(RatingsResources.self, from: data)
  • RatingsResources未正确实现。
let golfcourserating : [GolfCourseRating]?

应为:

let resources: [GolfCourseRating]?
  • 您的编码键实现错误,而不是:
enum CodingKeysRatings: String, CodingKey {

应改为:

enum CodingKeys: String, CodingKey {
4ngedf3f

4ngedf3f2#

您应该在结构RatingsResources处添加带有resources的枚举CodingKey
并解码:

if let response = try? JSONDecoder().decode(RatingsResources.self, from: data) {
  // Your response handler
}

相关问题