我有一个 API,我需要调用它来获取假期列表以及一些附加信息。我的 API 的链接 - http://mahindralylf.com/apiv1/getholidays
我使用网站 app.quicktype.io 创建的结构
struct Holiday: Codable {
let responseCode, responseMsg: String
let holidayCount: Int
let holidays: [HolidayElement]
enum CodingKeys: String, CodingKey {
case responseCode = "response_code"
case responseMsg = "response_msg"
case holidayCount = "holiday_count"
case holidays
}
}
struct HolidayElement: Codable {
let month: String
let image: String
let details: [Detail]
}
struct Detail: Codable {
let title, date, day: String
let color: Color
}
enum Color: String, Codable {
case b297Fe = "#B297FE"
case e73838 = "#E73838"
case the0D8464 = "#0D8464"
}
我可以找到“Holiday”对象,打印它,用“holidayCount”的颜色显示我的 tableViewCells。我想要做的是,在不使用正常的 json 解析和制作我自己的数组和字典的情况下,访问每个“假期”的“详细信息”。
tl;dr - 我需要知道如何访问假期元素的详细信息
谢谢!!
最佳答案
您的数据返回时带有一组 HolidayElements
,每个 HolidayElement
都有一组 Details
。
因此,对于每个 HolidayElement
,您都希望能够访问 details
数组。你会这样做:
let jsonResponse = try JSONDecoder().decode(Holiday.self, from: responseData)
print(jsonResponse.holidays[0].details)
这是一个 repo to play around with .
此外,您的编码 key 只是从 snake_case
转换而来,因此您实际上并不需要它们用于该端点。相反,您可以只告诉解码器 convertFromSnakeCase
在这种情况下,您可以放弃编码键,只需按如下方式解码:
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let jsonResponse = try decoder.decode(Holiday.self, from: responseData)
print(jsonResponse.holidays[0].details)
关于ios - 如何在 swift 中使用带有结构的嵌套 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52677119/