我正在尝试从Nutritionix API的自然语言处理器中查找食谱中每种成分的卡路里。我能够发送带有适当标头的POST请求并接收响应:但是我收到的JSON如下所示:
["foods": <__NSSingleObjectArrayI 0x6000037f8b50>(
{
"alt_measures" = (
{
measure = cup;
qty = 1;
seq = 1;
"serving_weight" = 240;
},
{
measure = g;
qty = 100;
seq = "<null>";
"serving_weight" = 100;
},
{
measure = tsp;
qty = 1;
seq = 101;
"serving_weight" = 5;
},
{
measure = tbsp;
qty = 1;
seq = 102;
"serving_weight" = 15;
}
);
"brand_name" = "<null>";
"consumed_at" = "2019-04-28T18:54:47+00:00";
"food_name" = "beef stock";
lat = "<null>";
lng = "<null>";
"meal_type" = 3;
metadata = {
"is_raw_food" = 0;
};
"ndb_no" = 6170;
"nf_calories" = "62.4";
"nf_cholesterol" = 0;
"nf_dietary_fiber" = 0;
"nf_p" = "148.8";
"nf_potassium" = 888;
"nf_protein" = "9.460000000000001";
"nf_saturated_fat" = "0.17";
"nf_sodium" = "950.4";
"nf_sugars" = "2.59";
"nf_total_carbohydrate" = "5.76";
"nf_total_fat" = "0.43";
"nix_brand_id" = "<null>";
"nix_brand_name" = "<null>";
"nix_item_id" = "<null>";
"nix_item_name" = "<null>";
photo = {
highres = "https://d2xdmhkmkbyw75.cloudfront.net/69_highres.jpg";
"is_user_uploaded" = 0;
thumb = "https://d2xdmhkmkbyw75.cloudfront.net/69_thumb.jpg";
};
"serving_qty" = 2;
"serving_unit" = cups;
"serving_weight_grams" = 480;
source = 1;
"sub_recipe" = "<null>";
tags = {
"food_group" = "<null>";
item = "beef stock";
measure = cups;
quantity = "2.0";
"tag_id" = 69;
};
upc = "<null>";
}
)
]
我需要“ nf_calories”的值。如何访问这些数据?这是代码:
func getCalories(ings: [Ingredient]) -> Void
{
var queryString = ""
for i in ings
{
if i.measurement != nil
{
queryString.append("\(i.amount.numerator)/\(i.amount.denominator) \(i.measurement!) \(i.name), ")
}
else
{
queryString.append("\(i.amount.numerator)/\(i.amount.denominator) \(i.name), ")
}
}
let string = "https://trackapi.nutritionix.com/v2/natural/nutrients"
let url = NSURL(string: string)
let request = NSMutableURLRequest(url: url! as URL)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("***", forHTTPHeaderField: "x-app-id")
request.addValue("***", forHTTPHeaderField: "x-app-key")
request.addValue("0", forHTTPHeaderField: "x-remote-user-id")
request.httpMethod = "POST"
let json: [String:Any] = ["query":queryString, "timezone":"US/Central"]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No Data")
return
}
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = responseJSON as? [String:Any]
{
print("\(responseJSON)")
if let d = responseJSON["foods"] as? [[String:Any]], !d.isEmpty, let cals = d[0]["nf_calories"] as? String
{
print(cals)
}
}
}
task.resume()
}
我对Swift并没有太多的经验,我该怎么做才能进入NSSingleObjectArrayI并提取数据?我在另一篇文章中找到了一种方法,但是当我在代码中实现它时,该方法不起作用。这是完成项目的最后一件事,我非常感谢您的帮助。