使用可选值 Swift 4 解码嵌套 JSON

Posted

技术标签:

【中文标题】使用可选值 Swift 4 解码嵌套 JSON【英文标题】:Decoding Nested JSON with Optional Values Swift 4 【发布时间】:2018-09-18 00:50:25 【问题描述】:

我正在尝试从这个 url https://jsonodds.com/api/test/odds 解码这个 JSON

有时有些值是 nil,我想避免让我的所有属性都是可选的,所以我尝试实现自定义解码。

[
    
        "ID": "e83bf033-dbde-49ac-a073-d385ebdc66d1",
        "HomeTeam": "Xavier",
        "AwayTeam": "Marquette",
        "Sport": 2,
        "MatchTime": "2018-01-24T23:30:00",
        "Odds": [
            
                "ID": "50742eed-a1c8-4958-8678-50627ffb665e",
                "EventID": "e83bf033-dbde-49ac-a073-d385ebdc66d1",
                "MoneyLineHome": "0",
                "MoneyLineAway": "0",
                "PointSpreadHome": "-4.0",
                "PointSpreadAway": "4.0",
                "PointSpreadHomeLine": "-110",
                "PointSpreadAwayLine": "-110",
                "TotalNumber": "78.0",
                "OverLine": "-115",
                "UnderLine": "-105",
                "DrawLine": "0",
                "LastUpdated": "2018-01-24T20:50:17",
                "SiteID": 3,
                "OddType": "First Half"
            ,
            
                "ID": "e83bf033-dbde-49ac-a073-d385ebdc66d1",
                "EventID": "e83bf033-dbde-49ac-a073-d385ebdc66d1",
                "MoneyLineHome": "-305",
                "MoneyLineAway": "255",
                "PointSpreadHome": "-7.0",
                "PointSpreadAway": "7.0",
                "PointSpreadHomeLine": "-112",
                "PointSpreadAwayLine": "-108",
                "TotalNumber": "162.5",
                "OverLine": "-104",
                "UnderLine": "-116",
                "DrawLine": "0",
                "LastUpdated": "2018-01-24T20:50:17",
                "SiteID": 3,
                "OddType": "Game"
            
        ],
        "Details": "Marquette at Xavier",
        "HomeROT": "720",
        "AwayROT": "719"
    ,

我目前有这个,但我不知道我是否正在考虑值何时为零,并且由于 JSON 中的“Odds”键是一个数组,所以我也正在努力使其工作,所以我不确定如何去做。当 JSON 中的“OddType”等于“Game”时,我只需要“Odds”。在我从 JSON 中获取所有数据后,我只是想过滤掉它,因为我不确定在解析 JSON 时是否有办法做到这一点。

struct GameInformation: Codable     
    let homeTeam: String
    let awayTeam: String
    let sport: Int
    let matchTime: String
    let odds: [Odds]
    let details: String


struct Odds: Codable 
    let moneyLineHome: String
    let moneyLineAway: String
    let pointSpreadHome: String
    let pointSpreadAway: String
    let pointSpreadHomeLine: String
    let pointSpreadAwayLine: String
    let totalNumber: String
    let overLine: String
    let underLine: String
    let drawLine: String
    let lastUpdated: String
    let oddType: String


extension Odds 
    enum CodingKeys: String, CodingKey 
        case moneyLineHome = "MoneyLineHome"
        case moneyLineAway = "MoneyLineAway"
        case pointSpreadHome = "PointSpreadHome"
        case pointSpreadAway = "PointSpreadAway"
        case pointSpreadHomeLine = "PointSpreadHomeLine"
        case pointSpreadAwayLine = "PointSpreadAwayLine"
        case totalNumber = "TotalNumber"
        case overLine = "OverLine"
        case underLine = "UnderLine"
        case drawLine = "DrawLine"
        case lastUpdated = "LastUpdated"
        case oddType = "OddType"
    

    enum OddsKey: String, CodingKey 
        case odds = "Odds"
    

    init(from decoder: Decoder) throws 
        let container = try decoder.container(keyedBy: OddsKey.self)
        let oddsContainer = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .odds)

        moneyLineHome = try oddsContainer.decodeIfPresent(String.self, forKey: .moneyLineHome) ?? "N/A"
        moneyLineAway = try oddsContainer.decodeIfPresent(String.self, forKey: .moneyLineAway) ?? "N/A"
        pointSpreadHome = try oddsContainer.decodeIfPresent(String.self, forKey: .pointSpreadHome) ?? "N/A"
        pointSpreadAway = try oddsContainer.decodeIfPresent(String.self, forKey: .pointSpreadAway) ?? "N/A"
        pointSpreadHomeLine = try oddsContainer.decodeIfPresent(String.self, forKey: .pointSpreadHomeLine) ?? "N/A"
        pointSpreadAwayLine = try oddsContainer.decodeIfPresent(String.self, forKey: .pointSpreadAwayLine) ?? "N/A"
        totalNumber = try oddsContainer.decodeIfPresent(String.self, forKey: .totalNumber) ?? "N/A"
        overLine = try oddsContainer.decodeIfPresent(String.self, forKey: .overLine) ?? "N/A"
        underLine = try oddsContainer.decodeIfPresent(String.self, forKey: .underLine) ?? "N/A"
        drawLine = try oddsContainer.decodeIfPresent(String.self, forKey: .drawLine) ?? "N/A"
        lastUpdated = try oddsContainer.decodeIfPresent(String.self, forKey: .lastUpdated) ?? "N/A"
        oddType = try oddsContainer.decodeIfPresent(String.self, forKey: .oddType) ?? "N/A"
    


extension GameInformation 
    enum CodingKeys: String, CodingKey 
        case homeTeam = "HomeTeam"
        case awayTeam = "AwayTeam"
        case sport = "Sport"
        case matchTime = "MatchTime"
        case odds = "Odds"
        case details = "Details"
    

    init(from decoder: Decoder) throws 
        let container = try decoder.container(keyedBy: CodingKeys.self)
        homeTeam = try container.decodeIfPresent(String.self, forKey: .homeTeam) ?? "N/A"
        awayTeam = try container.decodeIfPresent(String.self, forKey: .awayTeam) ?? "N/A"
        sport = try container.decodeIfPresent(Int.self, forKey: .sport) ?? 20
        matchTime = try container.decodeIfPresent(String.self, forKey: .matchTime) ?? "N/A"
        details = try container.decodeIfPresent(String.self, forKey: .details) ?? "N/A"
        odds = [try Odds(from: decoder)]
    

非常感谢任何帮助!

【问题讨论】:

【参考方案1】:

尝试在 GameInformation init 中设置这样的赔率:

odds = try container.decode(Array<Odds>.self, forKey: .odds)

接下来您应该删除 OddsKey 枚举并更新 Odds init:

init(from decoder: Decoder) throws 
    let container = try decoder.container(keyedBy: CodingKeys.self)

    moneyLineHome = try container.decodeIfPresent(String.self, forKey: .moneyLineHome) ?? "N/A"
    moneyLineAway = try container.decodeIfPresent(String.self, forKey: .moneyLineAway) ?? "N/A"
    pointSpreadHome = try container.decodeIfPresent(String.self, forKey: .pointSpreadHome) ?? "N/A"
    pointSpreadAway = try container.decodeIfPresent(String.self, forKey: .pointSpreadAway) ?? "N/A"
    pointSpreadHomeLine = try container.decodeIfPresent(String.self, forKey: .pointSpreadHomeLine) ?? "N/A"
    pointSpreadAwayLine = try container.decodeIfPresent(String.self, forKey: .pointSpreadAwayLine) ?? "N/A"
    totalNumber = try container.decodeIfPresent(String.self, forKey: .totalNumber) ?? "N/A"
    overLine = try container.decodeIfPresent(String.self, forKey: .overLine) ?? "N/A"
    underLine = try container.decodeIfPresent(String.self, forKey: .underLine) ?? "N/A"
    drawLine = try container.decodeIfPresent(String.self, forKey: .drawLine) ?? "N/A"
    lastUpdated = try container.decodeIfPresent(String.self, forKey: .lastUpdated) ?? "N/A"
    oddType = try container.decodeIfPresent(String.self, forKey: .oddType) ?? "N/A"

我还没有测试过,但它应该可以工作。问题是,我们应该将 Odds 解析为它的 init 内的单个对象,以及 GameInformation init 内的一个集合。我希望这是有道理的。

我认为最好在解析后进行过滤,您可以在 GameInformation init 中像这样初始化赔率(但如果不使用可选项,它似乎不正确):

odds = try container.decode(Array<Odds>.self, forKey: .odds).filter 
        let mirror = Mirror(reflecting: $0)
        return !mirror.children.contains(where:  _, value in
            if let v = value as? String, v == "N/A" 
                return true
             else 
                return false
            
        )
    

【讨论】:

成功了,非常感谢。在解析 JSON 时是否有过滤掉具有“N/A”作为其属性之一的对象,或者是在解析完所有 JSON 后最好的方法? 我添加了一种方法,您可以在我的答案中过滤赔率。

以上是关于使用可选值 Swift 4 解码嵌套 JSON的主要内容,如果未能解决你的问题,请参考以下文章

Swift 中的可选类型错误:致命错误:在展开可选值时意外发现 nil

Swift 中的可选值是啥?

致命错误:在快速 Json 解析中展开可选值时意外发现 nil

可选值是啥意思?

对 swift 中的可选值感到困惑

为啥你可以在 Swift 中为可选类型分配非可选值?