如何解码已经具有不同 API 解码逻辑的对象?

问题描述

所以我像这样解码了一个 JSON,

class MatchDetailResponse: Codable {

static let DocumentsDirectory = FileManager().urls(for: .documentDirectory,in: .userDomainMask).first!
static let ArchiveURL = DocumentsDirectory.appendingPathComponent("MatchDetailResponse")

var homeTeam: Team?
var awayTeam: Team?

enum CodingKeys: String,CodingKey {
    case homeTeam
    case awayTeam
}

func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    try container.encode(homeTeam,forKey: .homeTeam)
    try container.encode(awayTeam,forKey: .awayTeam)
}

private enum TopLevelKeys: String,CodingKey {
    case teams = "Teams"
    case matchDetail = "Matchdetail"
}

private enum MatchDetailKeys: String,CodingKey {
    case homeTeam = "Team_Home"
    case awayTeam = "Team_Away"
}

private struct DynamicCodingKeys: CodingKey {
    var stringValue: String
    init?(stringValue: String) {
        self.stringValue = stringValue
    }

    var intValue: Int?
    init?(intValue: Int) {
        return nil
    }
}

required init(from decoder: Decoder) throws {
    
    let container = try decoder.container(keyedBy: TopLevelKeys.self)
    let matchDetailContainer = try container.nestedContainer(keyedBy: MatchDetailKeys.self,forKey: .matchDetail)
    let homeTeamId = try matchDetailContainer.decode(String.self,forKey: MatchDetailKeys.homeTeam)
    let awayTeamId = try matchDetailContainer.decode(String.self,forKey: MatchDetailKeys.awayTeam)

    let teamContainer = try container.nestedContainer(keyedBy: DynamicCodingKeys.self,forKey: .teams)
    //Assign the home team & away team
    for key in teamContainer.allKeys {
        if key.stringValue == homeTeamId {
            homeTeam = try teamContainer.decode(Team.self,forKey: DynamicCodingKeys(stringValue: key.stringValue)!)
        }
        else if key.stringValue == awayTeamId {
            awayTeam = try teamContainer.decode(Team.self,forKey: DynamicCodingKeys(stringValue: key.stringValue)!)
        }
    }
}
}

如您所见,我收到了来自 API 的响应,我正在对其进行解码,一切正常。现在我的要求是存储它。所以我把它编码成这样。现在的问题是它何时会尝试解码存储的版本,因为解码函数是为 API 响应构建的,因此无法对其进行解码。

我的要求是,如何解码存储的 Codable 结构,以及我们究竟是如何做到的?任何帮助将不胜感激。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)