如何使用SwiftyJson与Alamofire解析树形嵌套的产品分类JSON数据
树形分类JSON解析方案(SwiftyJSON + Alamofire)
1. 定义递归数据模型
先定义适配嵌套结构的分类模型,children字段为可选的同类型数组,适配任意层级的嵌套:
import Foundation struct ProductCategory { /// 分类ID let id: String /// 分类名称 let name: String /// 父级分类ID let parentId: String /// 子分类列表,无下级分类时为nil let children: [ProductCategory]? }
2. 编写递归解析方法
因为分类结构是递归嵌套的,所以通过递归方法完成任意层级的解析:
import SwiftyJSON private func parseCategory(json: JSON) -> ProductCategory { var childrenList: [ProductCategory]? // 存在子分类时递归解析 if let childrenJsonArr = json["children"].array { childrenList = childrenJsonArr.map { subJson in parseCategory(json: subJson) } } return ProductCategory( id: json["id"].stringValue, // 可根据需求去掉分类名前后的空格 name: json["text"].stringValue.trimmingCharacters(in: .whitespaces), parentId: json["parent_id"].stringValue, children: childrenList ) }
3. 结合Alamofire发起请求并解析
import Alamofire import SwiftyJSON func requestCategoryData() { AF.request("你的分类接口地址", method: .get).responseJSON { response in switch response.result { case .success(let value): let rootJson = JSON(value) var rootCategories: [ProductCategory] = [] // 最外层为动态key,直接遍历所有值即可,无需硬编码key rootJson.forEach { (_, categoryJson) in let rootCate = parseCategory(json: categoryJson) rootCategories.append(rootCate) } // 此处rootCategories即为解析完成的全部分类树,可执行后续UI刷新等操作 print("解析完成的根分类:\(rootCategories)") case .failure(let error): print("接口请求失败:\(error.localizedDescription)") } } }
注意事项
- 解析方法可自动适配任意深度的子分类嵌套,无需修改代码
- 如果业务需要平铺展示全部分类,可额外写递归方法遍历分类树,把所有节点展开为一维数组
- 若接口返回的分类名称不存在前置空格,可去掉
trimmingCharacters相关的去空格处理
内容的提问来源于stack exchange,提问作者Dimitra
相关产品推荐
相关产品推荐

