代码之家  ›  专栏  ›  技术社区  ›  Noodledew

核心数据和解码:在json中进一步提升层次结构

  •  0
  • Noodledew  · 技术社区  · 6 年前

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

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

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

    但是,如何挖掘json文件的层次结构并访问时间呢?

    2 回复  |  直到 6 年前
        1
  •  0
  •   paresh    6 年前
        struct Currently: Codable {
          let time: Int
        ...
        }
    
        let myStructDictionary = try container.decode([String: Currently].self, from: json)
    myStructDictionary.forEach { print("\($0.key): \($0.value)") }
    

    希望这有帮助。

        2
  •  0
  •   Noodledew    6 年前
    let currently = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .currently)
    time = try currently.decode(Int.self, forKey: .time)