試圖獲取下面的 JSON 資料。除了foodNutrients,我什么都可以。運行以下代碼時,我收到以下資訊
結果: MealJournal.FoodNutrients(foodNutrients: nil)
{
"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"
},
我將如何去獲取食物營養素?
我有以下代碼,我得到以下結果
代碼:
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()
}
}
uj5u.com熱心網友回復:
食物營養素結構錯誤,需要匹配json。使用https://app.quicktype.io/生成正確的類/結構
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/455076.html
