json - 如何在枚举中自定义原始值
问题描述
我的 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 中的日期键不断变化,我需要动态键。我想在我的 Model 中的枚举中使用此方法:
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)
}
推荐阅读
- c# - 继续取消的任务
- python - 如何在 Python 中从 JSON 中的特定键打印特定值
- web-services - Java EE Webservice - 如何在没有数据库的情况下保存 json
- react-native - 带有标签的视差反应原生
- mongodb - 为什么猫鼬的 find() 给出了这个奇怪的结果,带有对象数组
- laravel - 如何将自定义数据添加到 laravel 队列作业表中或将队列作业有效负载添加到其他数据中
- delphi - FormStyle = fsMDIForm 在主窗体上的框架
- typescript - 为什么 typeof 变量在打字稿中未定义?
- asp.net-core - Core 2.1 HttpRequest.Body 尝试读取时为空
- google-cloud-platform - 谷歌源代码库集成