json - 如何自定义枚举中的原始值

标签 json swift enums codable

我的 json 是什么样的:

{
    "2019-08-27 19:00:00": {
        "temperature": {
            "sol":292
        }
    }
,
    "2019-08-28 19:00:00": {
        "temperature": {
            "sol":500
        }
    }
}

这是一种以所需格式获取当前 future 五天的方法:

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]

解码这样,

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)
}

关于json - 如何自定义枚举中的原始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57710378/

相关文章:

java - 使用枚举接口(interface)

mysql - spring JPA java.sql.Date 接受无效日期

javascript - 使用 jsonix 添加自定义 xsi 命名空间

ios - 将对象附加到变量

ios - 沿路径移动 Sprite

ios - 如何连续调用以在 Swift 中下拉分页数据

java - 在java中使用命令行接受文件名

typescript - 向枚举添加描述属性并在 TypeScript 中读取此描述

java - 用于保存类(class)、学生和作业数据的 JSON

java - com.android.volley.parse 错误 org.json.jsonexception java.lang.string 类型的值无法在 Android Volley 中转换为 jsonArray