无法解析API,需要转换为JSON对象-错误
我试图遵循这个API文档,它声明传入API密钥和json对象,尽管它不断返回错误 它说请求的内容必须是一个JSON对象,并且成分必须是一个数组 我不知道我是做错了还是API坏了。我确实得到了另一个API调用来工作,但营养素部分没有无法解析API,需要转换为JSON对象-错误,json,swift,swift4,Json,Swift,Swift4,我试图遵循这个API文档,它声明传入API密钥和json对象,尽管它不断返回错误 它说请求的内容必须是一个JSON对象,并且成分必须是一个数组 我不知道我是做错了还是API坏了。我确实得到了另一个API调用来工作,但营养素部分没有 curl -d @food.json -H "Content-Type: application/json" "https://api.edamam.com/api/food-database/nutrients?app_id=${YOUR_APP_ID}&a
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()
错误消息:[消息:无法解析实体,错误:错误请求]当我将此与API文档进行比较时,我可以看到两个需要修复的错误: 你错过了产量领域。 配料应该是一个数组。 我刚刚用这个JSON对象进行了测试,效果很好:
let json: [String: Any] = [
"yield": 1,
"ingredients": [
[
"quantity": 1,
"measureURI": "http://www.edamam.com/ontologies/edamam.owl#Measure_pound",
"foodURI": "http://www.edamam.com/ontologies/edamam.owl#Food_USDABR_45039390"
]
]
]
您需要通过JSONSerialization。Swift 4有JSONECODER。@马特,我不是在解码,我是在编码,然后是JSONECODER。甚至更好。是时候结束JSONSerialization了。