【问题标题】:Can't parse API, need to convert to JSON Object - Error无法解析 API,需要转换为 JSON 对象 - 错误
【发布时间】: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 了。

标签: json swift swift4


【解决方案1】:

当我将其与 API 文档进行比较时,我发现有两个需要修复的错误:

  1. 您缺少yield 字段。
  2. 成分应该是一个数组。

我刚刚用这个 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"
    ]
  ]
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    相关资源
    最近更新 更多