奇怪的JSON API响应SWIFT

时间:2018-04-18 15:00:27

标签: ios json swift http post

我正在向swift中的API发送HTTP POST请求,它应该响应:

    {
      "results": [
        {
          "alternatives": [
            {
              "transcript": "how old is the Brooklyn Bridge",
              "confidence": 0.98267895
            }
          ]
        }
      ]
    }

但是,我通过print(jsonResponse)函数接收到它:

Optional({
    results =     (
                {
            alternatives =             (
                                {
                    confidence = "0.9688848";
                    transcript = "how old is the Brooklyn Bridge";
                }
            );
        }
    );
})

有没有理由说明为什么响应没有以API文档中指出的正确格式到达?我需要解码响应以获得"成绩单"值。但是,我收到以下错误:

keyNotFound(CodingKeys(stringValue: "transcript", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"transcript\", intValue: nil) (\"transcript\").", underlyingError: nil))

也许我的要求不是最优的......这是我的代码,感谢任何帮助!

let parameters = ["config": ["encoding": "FLAC", "sampleRateHertz": "16000", "languageCode": "en-AU"], "audio": ["uri":"gs://cloud-samples-tests/speech/brooklyn.flac"]]

guard let url = URL(string: "https://speech.googleapis.com/v1/speech:recognize?key=AIzaSyDqYpPQIabwF5L-WibBxtVsWRBrc8uKi4w") else {return}

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

do {
    request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: []) // pass dictionary to nsdata object and set it as request body
} catch let error {
    print(error.localizedDescription)
}

URLSession.shared.dataTask(with: request) { (data , response , error) in

    guard let data = data else {return}

    do {
        let jsonResponse = (try? JSONSerialization.jsonObject(with: data, options: []))
        print("\(jsonResponse)")

        let course =  try JSONDecoder().decode(Course.self , from : data)
        print(course.transcript)       
    } catch {

        print(error)
    }
}.resume()

这是我的课程代码块:我是否需要在结构和成绩单中包含其他组件?

struct Course: Decodable {
    let transcript: String
    enum CodingKeys: String, CodingKey {
        case transcript = "transcript"
    }
}

1 个答案:

答案 0 :(得分:2)

jsonResponse是一个可选字典,这就是为什么它的调试description看起来像你打印的而不是你想要的纯JSON。您的问题可能是您的Decodeable对象未正确设置 - 因为它的外观只有一个Course。您可能还需要两个Response,其中包含Alternative个列表。然后在Alternative中,您有一个Course的列表。

像这样构建你的对象,它应该可以解决这个问题:

struct Response: Decodable {
    let results: [Alternative]
}

struct Alternative: Decodable {
    let alternatives: [Course]
}

struct Course: Decodable {
    let transcript: String
    let confidence: Float
}

然后换掉这一行:

let course =  try JSONDecoder().decode(Course.self , from : data)

有了这个改变:

let course = try JSONDecoder().decode(Response.self, from: data).results[0].alternatives[0]