【问题标题】:Core Data & Decode: Go one hierarchy step further in json核心数据和解码:在 json 中更进一步的层次结构
【发布时间】:2023-04-01 00:24:01
【问题描述】:

我的 Api(json) 看起来像这样:

"timezone": "America/Los_Angeles",
"currently": {
    "time": 1534941429,
    ...
},

使用我的代码,我可以按如下方式访问时区:

timezone = try container.decode(Double.self, forKey: .timezone)

但是我怎样才能挖掘到我的 json 文件的层次结构并访问时间呢?

【问题讨论】:

  • 这和 Core Data 有什么关系?
  • 如果没有核心数据,我什至不需要初始化容器并从那里解码。

标签: ios json swift core-data decode


【解决方案1】:
    struct Currently: Codable {
      let time: Int
    ...
    }

    let myStructDictionary = try container.decode([String: Currently].self, from: json)
myStructDictionary.forEach { print("\($0.key): \($0.value)") }

希望这会有所帮助。

【讨论】:

    【解决方案2】:
    let currently = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .currently)
    time = try currently.decode(Int.self, forKey: .time)
    

    这就是它所需要的。希望这对任何人都有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-18
      • 1970-01-01
      • 1970-01-01
      • 2015-12-08
      • 2019-12-07
      • 1970-01-01
      相关资源
      最近更新 更多