Swift 5 解析USDA FoodData Central接口返回的特殊格式数据
问题根源拆解
你打印到控制台的内容不是原始JSON报文,这是JSONSerialization将接口响应解析为Foundation对象(NSDictionary/NSArray)后,系统生成的调试描述:
- 大括号
{}对应字典结构 - 小括号
()对应数组结构 - 键值对用
=连接foodNutrients后面的括号没有特殊含义,它本质是一个标准JSON数组,只是被打印成了小括号包裹的形式。
你之前解析报错的核心原因有两个:
- 错误将数组类型的
foodNutrients定义为单个嵌套结构体,类型完全不匹配 - USDA接口的
id、amount字段返回类型不统一(同一字段可能返回整数、浮点数或带引号的字符串),直接绑定固定Swift类型必然触发解码失败
适配接口的正确解码实现
分层定义对应结构
按照接口的真实嵌套层级,从最内层嵌套对象到根节点依次定义Decodable结构:
// 匹配nutrient嵌套对象的属性 struct Nutrient: Decodable { let id: Int let name: String let number: String let rank: Int let unitName: String } // 匹配foodNutrients数组中的单个营养条目 struct FoodNutrient: Decodable { let amount: Double let id: String let nutrient: Nutrient let type: String } // 匹配接口返回的根节点结构 struct Root: Decodable { let description: String let fdcId: Int let dataType: String // 修正类型:foodNutrients是数组,不是单个对象 let foodNutrients: [FoodNutrient] }
兼容混合类型字段
从你的打印输出可以看到,同一字段存在类型不一致的情况:比如id字段一次返回纯数字9141826,一次返回字符串"9141827";amount字段返回字符串格式的"24.09"。需要自定义解码逻辑做类型兼容,避免解码中断:
extension FoodNutrient { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) // 兼容数字/字符串格式的id if let idNum = try? container.decode(Int.self, forKey: .id) { id = String(idNum) } else { id = try container.decode(String.self, forKey: .id) } // 兼容数字/字符串格式的amount if let amountNum = try? container.decode(Double.self, forKey: .amount) { amount = amountNum } else if let amountStr = try? container.decode(String.self, forKey: .amount), let parsedAmount = Double(amountStr) { amount = parsedAmount } else { // 异常值兜底 amount = 0 } nutrient = try container.decode(Nutrient.self, forKey: .nutrient) type = try container.decode(String.self, forKey: .type) } enum CodingKeys: String, CodingKey { case amount, id, nutrient, type } }
避坑提示
- 调试时不要把控制台打印的Foundation对象描述当成真实JSON结构,直接打印接口返回的原始
Data转成的utf8字符串,才能看到准确的JSON格式 - 第三方公共API经常存在字段类型不统一的问题,对数值类字段一定要做类型兜底,避免单条异常数据导致全量解码失败
- 数组类型的JSON字段,对应的Swift类型必须是元素组成的数组,不要错误定义为单个对象
内容的提问来源于stack exchange,提问作者Nobadi
相关产品推荐
相关产品推荐

