我的json是什么样子的:
{
"2019-08-27 19:00:00": {
"temperature": {
"sol":292
}
}
,
"2019-08-28 19:00:00": {
"temperature": {
"sol":500
}
}
}
这是一种以所需格式获取当前未来五天的方法:
func getFormatedDates() -> [String] {
let date = Date()
let format = DateFormatter()
format.dateFormat = "yyyy-MM-dd"
var dateComponents = DateComponents()
var dates = [String]()
for i in 0...4 {
dateComponents.setValue(i, for: .day)
guard let nextDay = Calendar.current.date(byAdding: dateComponents, to: date) else { return [""] }
let formattedDate = format.string(from: nextDay)
dates.append(formattedDate + " " + "19:00:00")
}
return dates
}
由于 API 中的日期键不断变化,因此我需要动态键。我想在枚举中使用此方法,就像在我的模型中一样:
var dates = getFormatedDates()
let firstForcast: FirstForcast
let secondForcast: SecondForcast
enum CodingKeys: String, CodingKey {
case firstForcast = dates[0]
case secondForcast = dates[1]
}
有什么想法吗?
创建相关类型,如下所示,
// MARK: - PostBodyValue
struct PostBodyValue: Codable {
let temperature: Temperature
}
// MARK: - Temperature
struct Temperature: Codable {
let sol: Int
}
typealias PostBody = [String: PostBodyValue]
decode
这样,
do {
let data = // Data from the API
let objects = try JSONDecoder().decode(PostBody.self, from: data)
for(key, value) in objects {
print(key)
print(value.temperature.sol)
}
} catch {
print(error)
}