我正在使用 Rest API 服务,其中响应分为基本响应,所有其他响应都继承自它。
我正在尝试使用解码器接口为我的响应模型类构建相同的结构。
但是我在继承类的解码方面遇到问题。
我试图关注这个问题:在 Swift 4 中使用 Decodable 和继承 https://stackoverflow.com/questions/44553934/using-decodable-in-swift-4-with-inheritance
但没有运气。
这是初始结构:
class LoginResponse: BaseResponse{
var Message: String?
private enum CodingKeys: String, CodingKey{
case Message
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
Message = try container.decode(String.self, forKey: .Message)
let superDecoder = try container.superDecoder()
try super.init(from: superDecoder)
}
}
class BaseResponse: Decodable {
var Status: Int?
private enum CodingKeys: String, CodingKey{
case Status
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self) // This line throws the exception
Status = try container.decode(Int.self, forKey: .Status)
}
}
这是我尝试解码的方式:
let decoder = JSONDecoder()
let json = "{\"Message\":\"saa\",\"Status\":200}"
let login = try! decoder.decode(LoginResponse.self, from: json.data(using: .utf8)!)
正如我上面所写,这一行抛出异常(在 BaseResponse 类中)
let container = try decoder.container(keyedBy: CodingKeys.self)
Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.valueNotFound(Swift.KeyedDecodingContainer<SampleProject.BaseResponse.(CodingKeys in _084835F8074C7E8C5E442FE2163A7A00)>, Swift.DecodingError.Context(codingPath: [Foundation.(_JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue: "super", intValue: nil)], debugDescription: "Cannot get keyed decoding container -- found null value instead.", underlyingError: nil))
不知道如何处理。
提前致谢!