【发布时间】:2018-09-15 19:45:23
【问题描述】:
我正在尝试遵循这个 API 文档,该文档声明要传递您的 API 密钥和一个 json 对象,尽管它一直返回错误
它表示请求的内容必须是一个 JSON 对象,而 Ingredients 必须是一个数组。
我不知道是我做错了什么还是 API 坏了。我确实得到了另一个 API 调用,但不是用于营养部分。
curl -d @food.json -H "Content-Type: application/json" "https://api.edamam.com/api/food-database/nutrients?app_id=${YOUR_APP_ID}&app_key=${YOUR_APP_KEY}"
{
"yield": 1,
"ingredients": [
{
"quantity": 1,
"measureURI": "http://www.edamam.com/ontologies/edamam.owl#Measure_unit",
"foodURI": "http://www.edaman.com/ontologies/edamam.owl#Food_USDABR_45039390"
}
]
}
在我的代码中,这是我得到的:
let json: [String: Any] = [
"ingredients": ["quantity":1,
"measureURI":"http://www.edamam.com/ontologies/edamam.owl#Measure_pound",
"foodURI" : "http://www.edaman.com/ontologies/edamam.owl#Food_USDABR_45039390"]]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
// Nutrition API
let app_id = "51fkkff"
let app_key = "6503a430030768824iidkos03d431d94"
let urlString = String(format: "https://api.edamam.com/api/food-database/nutrients?app_id=%@&app_key=%@", app_id, app_key)
let url = URL(string: urlString)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { 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)
}
}
task.resume()
错误信息:["message": Entity could not be parsed, "error": bad_request]
【问题讨论】:
-
你需要通过 JSONSerialization。 Swift 4 有 JSONDecoder。
-
@matt 我不是在解码,我在编码
-
然后是 JSONEncoder。甚至更好。是时候克服 JSONSerialization 了。