我正在尝试使用以下方法将一些用于翻译的文本发布到 Yandex 翻译 api,但似乎返回了无效的 JSON。但是,我无法阅读我要返回的内容。有没有办法解析“数据”?这是方法
func getTranslated(text: String, lang: "en-fr", completion: @escaping (TranslationReturned?) -> Void) {
guard var components = URLComponents(string: translationUrl) else { return }
components.queryItems = [URLQueryItem(name: "key", value: translationKey),
URLQueryItem(name: "text", value: text),
URLQueryItem(name: "lang", value: lang),
URLQueryItem(name: "format", value: "plain"),
URLQueryItem(name: "options", value: String(1))]
var request = URLRequest(url: components.url!)
request.httpMethod = "POST"
URLSession.shared.dataTask(with: request) { (data, response, error) in
print("data in call to yandex is",data as Any)//79 bytes
if let error = error {
print("error is",error.localizedDescription)
completion(nil)
return
}
guard let data = data else {
print("no data")
completion(nil)
return
}
do {
let translation = try JSONDecoder().decode(TranslationReturned.self, from: data)
completion(translation)
} catch {
print(error)
completion(nil)
}
}.resume()
}
返回的项目长 79 个字节,错误为零,但我无法确定数据是什么。这是调试器显示的内容:
data in call to yandex is Optional(79 bytes)
typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "code", intValue: nil)], debugDescription: "Expected to decode String but found a number instead.", underlyingError: nil))
(lldb) po data
error: <EXPR>:3:1: error: use of unresolved identifier 'data'; did you mean 'Data'?
data
编辑:
这是 TransationReturned 对象的样子:
@objc public class TranslationReturned: NSObject, Codable {
var code: String = ""
var lang: String = ""
var text: String = ""
}
编辑 2
按照 rmaddy 的建议,转换为字符串后返回的 JSON:
{"code":200,"detected":{"lang":"en"},"lang":"en-fr","text":["Bonjour les ami"]}
我能够通过将 TranslationReturned 更改为处理 JSON 的结构来解决错误,如下所示:
@objc public class TranslationReturned: NSObject, Codable {
var code: Int = 0
var lang: String = ""
var text = [String]()
}