【问题标题】:How to properly declare Array type when initializing struct in Swift在 Swift 中初始化 struct 时如何正确声明 Array 类型
【发布时间】:2018-05-25 02:44:25
【问题描述】:

我正在尝试初始化一个结构,以便可以从 Swift 中的 JSON 文件进行解析。我写了以下内容:

struct StopDescription: Decodable {
    let stopId: String
    let translocStopId: String
    let stopName: String
    let stopDesc: String
    let stopLat: String
    let stopLon: String
    let directionId: String
    let times: [String]
}

为了从这个 JSON 代码中解析:

{
    stop_id: "M1",
    transloc_stop_id: "4160714",
    stop_name: "blank",
    stop_desc: "blank",
    stop_lat: "142",
    stop_lon: "-171",
    direction_id: "1",
    times: [
        "7:00 AM",
        "7:30 AM",
        "8:00 AM",
        "8:30 AM",
        "8:45 AM",
        "9:00 AM",
        "9:30 AM",
        "10:00 AM",
        "10:30 AM",
        "11:00 AM",
        "11:30 AM"
    ]
}

我不完全确定times 变量的数组声明是否正确。有人可以指出我正确的方向吗?

【问题讨论】:

  • 将代码作为格式化文本粘贴到问题中会容易得多。按照图片链接没有帮助。
  • 我很抱歉。我已经相应地编辑了评论。
  • 从技术上讲,您的 JSON 不是 JSON。您必须双引号键以及字符串值。如果您的 JSON 解析器运行失败,那可能就是问题所在。

标签: json swift


【解决方案1】:

是的,没错。解析 JSON 时,请务必添加 CodingKeys 枚举,或者最好使用 .convertFromSnakeCase 作为 keyDecodingStrategy

struct StopDescription: Codable {
    let stopId, translocStopId, stopName, stopDesc: String
    let stopLat, stopLon, directionId: String
    let times: [String]
}

let let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase

let stopDescription = try? decoder.decode(StopDescription.self, from: jsonData)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-24
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    相关资源
    最近更新 更多