2
レスポンスはBaseレスポンスに分割され、他のすべてのレスポンスはレスポンスを継承します。継承でデコード可能を使用すると例外が発生する
私は、Decoderインターフェイスを使用して、自分のレスポンスモデルクラスに同じ構造を構築しようとしています。
しかし、私は継承されたクラスのデコードに問題があります。
私はこの問題を追跡しようとした: 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))
どう対処するかわかりません。
ありがとうございました!
ありがとうございます!それは働いている!どうしたらいいですか?私が投稿した同様のリンクとどう違うのですか? – dor506
WWDCビデオのJSON構造があなたの質問と同じであるかどうかは疑問です。それにもかかわらず、私は 'superDecoder'がエラーを投げることを確認できます。 – vadian
私はそれを行うが、(LoginResponseとして)子クラスの値を取得しようとすると例外が発生するが、スーパーで(BaseResponseとして)何も検索しないが、デバッグは例外の説明を表示しなかった –