JSON响应中的Swift数据模型



我遇到了一个问题,为以下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

首先,在解码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 {
    

您应该在structRatingsResources上添加带有resources的enum CodingKey

和解码:

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

相关内容

  • 没有找到相关文章

最新更新