Swift解析JSON时for循环跳过代码及[String:Any]转[String]报错求助
问题根因
你遇到的两个问题均来自JSON结构和代码解析逻辑、模型定义不匹配:
- JSON中的
past_employers是数组类型(外层为[]包裹,每个元素是包含公司信息的字典),但你在guard判断中将其转换为[String: Any]单个字典,这一步直接判定失败,所有遍历都会走到else continue分支,自然无法将实例加入数组 - 类型报错是因为
Employee模型中pastEmployers被定义为[String]!字符串数组,但你传入的解析结果是字典/数组类型,二者不匹配 - 额外提醒:你的JSON结构中,员工顶级字段不存在
company和responsibilities,仅past_employers的子元素包含这两个字段,原有guard中对这两个字段的判定会永远失败
修复步骤
1. 调整数据模型定义
新增子模型对应past_employers的元素结构,同时修改Employee的属性类型:
// 新增过去雇主子模型 class PastEmployer { let company: String let responsibilities: [String] init(company: String, responsibilities: [String]) { self.company = company self.responsibilities = responsibilities } } // 修改Employee主模型 class Employee { let name: String let username: String let macaddress: String let currentTitle: String let skills: [String] let pastEmployers: [PastEmployer] // JSON中无对应顶级字段,改为可选类型避免解析失败 let currentCompany: String? let responsibilities: [String]? init(name: String, username: String, macaddress: String, currentTitle: String, skills: [String], pastEmployers: [PastEmployer], currentCompany: String?, responsibilities: [String]?) { self.name = name self.username = username self.macaddress = macaddress self.currentTitle = currentTitle self.skills = skills self.pastEmployers = pastEmployers self.currentCompany = currentCompany self.responsibilities = responsibilities } }
2. 修正解析逻辑
调整Parse方法中对past_employers的解析逻辑,删除不存在字段的判定:
func Parse(jsonObject: [Any]?) { guard let json = jsonObject else { print("Parse failed to unwrap the optional.") return } for firstLevelItems in json { guard let object = firstLevelItems as? [String: Any], let ename = object["employeename"] as? String, let eusername = object["username"] as? String, let emacaddress = object["macaddress"] as? String, let ecurrentTitle = object["current_title"] as? String, let eskills = object["skills"] as? [String], // past_employers转字典数组,而非单个字典 let epastEmployersArr = object["past_employers"] as? [[String: Any]] else { continue } // 遍历解析过去雇主数组 var pastEmployers = [PastEmployer]() for empDict in epastEmployersArr { guard let company = empDict["company"] as? String, let responsibilities = empDict["responsibilities"] as? [String] else { continue } pastEmployers.append(PastEmployer(company: company, responsibilities: responsibilities)) } // 生成实例加入数组 let emp = Employee( name: ename, username: eusername, macaddress: emacaddress, currentTitle: ecurrentTitle, skills: eskills, pastEmployers: pastEmployers, currentCompany: nil, responsibilities: nil ) employees.append(emp) } // 解析完成后调用展示方法 displayEmployee() }
3. 调整展示逻辑
数组类型无法直接赋值给UILabel的text属性,需要先拼接为字符串:
func displayEmployee() { // 避免数组为空崩溃 guard let firstEmp = employees.first else { return } empName.text = firstEmp.name empUsername.text = firstEmp.username // 技能数组用顿号拼接 empSkills.text = firstEmp.skills.joined(separator: "、") // 过去雇主信息拼接为多行文本 let pastEmpStr = firstEmp.pastEmployers.map { "· \($0.company): \($0.responsibilities.joined(separator: "、"))" }.joined(separator: "\n") pastEmployers.text = pastEmpStr }
额外修正
你获取JSON路径的代码中ofType参数不需要带点,修改为:
if let path = Bundle.main.path(forResource: "EmployeeData", ofType: "json" )
内容的提问来源于stack exchange,提问作者Molag_Bork
相关产品推荐
相关产品推荐

