【问题标题】:SwiftUi Decoding JSONSwiftUi 解码 JSON
【发布时间】:2020-09-25 20:18:09
【问题描述】:

我是 Swift 和 SwiftUi 的新手,我正在尝试解码 JSON 文件。我知道我必须使用 CodingKeys,但是当键是日期时我不知道该怎么做。

我的 JSON 如下所示:

{
    "2020-09-01": [
        "Tuesday",
        [],
        "N"
    ],
    "2020-09-02": [
        "Wednesday",
        [
          "12:00p"
        ],
        "N"
    ]
}

我的模型看起来像这样:

struct TimeStamp: Codable {
    var t =  [TimeStampForCurrentDay]()
}

struct TimeStampForCurrentDay: Codable {
    let day: String
    let times: [String]
    let type: String
}

我得到了这个错误

致命错误:“试试!”表达式意外引发错误:Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "t", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: "t ", intValue: nil) ("t").", 基础错误: nil))

当我尝试用这个函数解码时

try! JSONDecoder().decode(TimeStamp.self, from: responseData)

【问题讨论】:

    标签: json swift decode


    【解决方案1】:

    你有一个[String: [Any]] 类型的字典,它有点难以解码。要么你用JSONSerialization直接解码成这个字典类型

    do {
        let result = try JSONSerialization.jsonObject(with: data) as? [String: [Any]]
        //...
    } catch {
        print(error)
    }
    

    但是如果每个数组中值的顺序始终相同,即天/次/类型,那么我们可以使用自定义 init 进行解码以获取类型为 [String: TimeStampForCurrentDay] 的字典

    struct TimeStampForCurrentDay: Codable {
        let day: String
        let times: [String]
        let type: String
    
        init(from decoder: Decoder) throws {
            var container = try decoder.unkeyedContainer()
            day = try container.decode(String.self)
            times = try container.decode([String].self)
            type = try container.decode(String.self)
        }
    }
    
    do {
        let result = try JSONDecoder().decode([String: TimeStampForCurrentDay].self, from: data)
        print(result)
    } catch {
        print(error)
    }
    

    【讨论】:

    • 嘿,谢谢你第二个代码是我正在寻找的。祝你有美好的一天!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 2023-01-12
    • 1970-01-01
    相关资源
    最近更新 更多