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