如何在Swift中初始化struct时正确声明Array类型

时间:2018-05-24 15:08:03

标签: json swift

我试图初始化一个结构,以便我可以从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变量的数组声明是否正确。有人可以指出我正确的方向吗?

1 个答案:

答案 0 :(得分: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)