Api 使用 flurry api 请求 IOS

Api request IOS using flurry api

我有以下代码向 flurry.com API 端点发出 API 请求并解码请求。

let url = URL(string: bookStarRateDomainUrl)!

let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
  if let error = error {
    print("Error with fetching book star rates: \(error)")
    return
  }
  
  guard let httpResponse = response as? HTTPURLResponse,
        (200...299).contains(httpResponse.statusCode) else {
    print("Error with the response, unexpected status code: \(response)")
    return
  }

  if let data = data,
    let flurryItems = try? JSONDecoder().decode(FlurryItem.self, from: data) {
    completionHandler(flurryItems.results ?? [])
  }
})
task.resume()

问题是我无法使用 .decode(FlurryItem.self,因为我从 API 端点返回的值是这样的:

[{
     dateTime:2020-06-05 00:00:00.000-07:00
     event|name:BookStarRate
     paramName|name:bookId
     paramValue|name:why-buddism-is-true
     count:3
}]

注意变量名称是“paramName|name”。 |使得无法为该项目命名变量。我可以做什么?

1- 你需要使用枚举

struct Root: Codable { 
    var date: String
    var name: String  
    var id: Int
    var value: String
    var count: Int
    enum CodingKeys: String, CodingKey {
        case date = "dateTime" 
        case name = "event|name" 
        case id = "paramName|name" 
        case value = "paramValue|name" 
        case count  
    }
}

2- 你应该使用 [FlurryItem].self

let flurryItems = try? JSONDecoder().decode([FlurryItem].self, from: data)