我的Session
模型看起来像这样
public struct Session: Codable {
let name: String
let key: String
let subscriber: Int
}
我想使用Alamofire的responseData
方法调用API,并将接收到的数据解码为Session
对象,但是每次解码都会失败。
Alamofire.request(url, method: .post).responseData { response in
if let error = response.error {
failure?(error)
} else if let data = response.result.value {
do {
if let str = String(data: data, encoding: .utf8) {
// This prints out a correct JSON string
print(str)
}
let session = try JSONDecoder().decode(Session.self, from: data)
success(session.key)
} catch let DecodingError.keyNotFound(key, context) {
print("Key '\(key)' not found:", context.debugDescription)
print("codingPath:", context.codingPath)
} catch {
print(error.localizedDescription)
}
}
}
我在解码之前将Data的内容打印到控制台,它看起来像一个有效的JSON,并且我的模型中没有任何错字。解码失败的原因可能是什么?
控制台的输出:
{“会话”:{“订户”:0,“名称”:“ someuser”,“密钥”:“ somekey”}}
找不到键'CodingKeys(stringValue:“ name”,intValue:nil)':否 与键CodingKeys相关联的值(stringValue:“名称”,intValue: nil)(“名称”)。 codingPath:[]