如何在Swift中用Alamofire解码含无键元素的嵌套数组JSON
解决Alamofire .responseDecodable的自定义解码问题
针对你遇到的JSON结构,每个cue子项是包含时间戳和详情字典的数组,需要给CueItem实现自定义解码逻辑来适配这种无键的数组结构。
完整数据模型实现
import Foundation struct Response: Decodable { let p: Int let q: CueFeed } struct CueFeed: Decodable { let cue: [CueItem] } // 封装单个cue项的时间戳和详情内容 struct CueItem: Decodable { let timestamp: Int let content: CueContent // 自定义解码逻辑,适配无键数组结构 init(from decoder: Decoder) throws { // 将当前元素解码为无键容器(对应JSON中的数组) var container = try decoder.unkeyedContainer() // 依次取出数组的两个元素:时间戳、详情对象 timestamp = try container.decode(Int.self) content = try container.decode(CueContent.self) } } // 对应数组中第二个元素的详情字典 struct CueContent: Decodable { let done: Int let link: String let share: Int let tags: String let title: String }
代码说明
CueItem的自定义init方法通过unkeyedContainer()处理无键数组结构,按顺序解码数组内的两个元素,分别对应时间戳和详情内容。CueContent直接使用默认Decodable实现,因为它的字段与JSON字典的键完全匹配,无需额外处理。
Alamofire调用示例
使用.responseDecodable时直接指定根模型Response即可:
AF.request("你的目标接口URL") .responseDecodable(of: Response.self) { response in switch response.result { case .success(let decodedData): // 处理解码后的数据 print(decodedData.q.cue) case .failure(let error): // 处理解码错误 print(error) } }
内容的提问来源于stack exchange,提问作者libhut-samwes
相关产品推荐
相关产品推荐

