从嵌套 JSON 中抓取数据
Grab data from nested JSON
正在尝试获取以下 JSON 数据。除了食物营养素,我什么都能吃。当 运行 下面的编码时,我收到以下
结果:
MealJournal.FoodNutrients(食物营养素:无)
{
"fdcId":748967,
"description":"Eggs, Grade A, Large, egg whole",
"publicationDate":"12/16/2019",
"foodNutrients":[
{
"type":"FoodNutrient",
"nutrient":{
"id":1091,
"number":"305",
"name":"Phosphorus, P",
"rank":5600,
"unitName":"mg"
},
我该如何获取 foodNutrients?
我有以下代码,我得到了以下结果
代码:
struct FoodNutrients: Codable{
let foodNutrients: [String]?
enum CodingKeys: String, CodingKey{
case foodNutrients = "foodNutrients"
}
}
struct Food: Codable{
let dataType: String
let description: String
let fdcId: Int
let foodNutrients: [FoodNutrients]
}
class FoodApi {
func getFood (){
guard let url = URL(string: "https://api.nal.usda.gov/fdc/v1/food/748967?api_key=bRbzV0uKJyenEtd1GMgJJNh4BzGWtDvDZVOy8cqG") else { return }
URLSession.shared.dataTask(with: url) { (data, _, _) in
let results = try! JSONDecoder().decode(Food.self, from: data!)
print(results)
}
.resume()
}
}
食物营养素结构错误,需要与 json 匹配。使用 https://app.quicktype.io/ 生成正确的 classes/structs
正在尝试获取以下 JSON 数据。除了食物营养素,我什么都能吃。当 运行 下面的编码时,我收到以下
结果: MealJournal.FoodNutrients(食物营养素:无)
{
"fdcId":748967,
"description":"Eggs, Grade A, Large, egg whole",
"publicationDate":"12/16/2019",
"foodNutrients":[
{
"type":"FoodNutrient",
"nutrient":{
"id":1091,
"number":"305",
"name":"Phosphorus, P",
"rank":5600,
"unitName":"mg"
},
我该如何获取 foodNutrients?
我有以下代码,我得到了以下结果
代码:
struct FoodNutrients: Codable{
let foodNutrients: [String]?
enum CodingKeys: String, CodingKey{
case foodNutrients = "foodNutrients"
}
}
struct Food: Codable{
let dataType: String
let description: String
let fdcId: Int
let foodNutrients: [FoodNutrients]
}
class FoodApi {
func getFood (){
guard let url = URL(string: "https://api.nal.usda.gov/fdc/v1/food/748967?api_key=bRbzV0uKJyenEtd1GMgJJNh4BzGWtDvDZVOy8cqG") else { return }
URLSession.shared.dataTask(with: url) { (data, _, _) in
let results = try! JSONDecoder().decode(Food.self, from: data!)
print(results)
}
.resume()
}
}
食物营养素结构错误,需要与 json 匹配。使用 https://app.quicktype.io/ 生成正确的 classes/structs