Parsing Nested JSON in SWIFT 4

前端 未结 1 568
说谎
说谎 2021-01-03 00:32

I am currently parsing JSON with Decodable in SWIFT 4.

The JSON is formatted as follows:

  {
  \"autopayout_from\": \"1.010\",
  \"earning_24_hours\"         


        
相关标签:
1条回答
  • 2021-01-03 01:23

    Here's how I would model this:

    struct Ticker: Codable {
        let autopayoutFrom, earning24_Hours: String
        let error: Bool
        let immatureEarning: Double
        let lastPaymentAmount, lastPaymentDate, lastShareDate: String
        let payoutDaily, payoutRequest: Bool
        let totalHashrate, totalHashrateCalculated, transferringToBalance: Double
        let wallet, walletBalance: String
        let workers: [String: Worker]
    
        enum CodingKeys: String, CodingKey {
            case autopayoutFrom = "autopayout_from"
            case earning24_Hours = "earning_24_hours"
            case error
            case immatureEarning = "immature_earning"
            case lastPaymentAmount = "last_payment_amount"
            case lastPaymentDate = "last_payment_date"
            case lastShareDate = "last_share_date"
            case payoutDaily = "payout_daily"
            case payoutRequest = "payout_request"
            case totalHashrate = "total_hashrate"
            case totalHashrateCalculated = "total_hashrate_calculated"
            case transferringToBalance = "transferring_to_balance"
            case wallet
            case walletBalance = "wallet_balance"
            case workers
        }
    }
    
    struct Worker: Codable {
        let alive: Bool
        let hashrate: Double
        let hashrateBelowThreshold: Bool
        let hashrateCalculated: Double
        let lastSubmit: String
        let secondSinceSubmit: Int
        let worker: String
    
        enum CodingKeys: String, CodingKey {
            case alive, hashrate
            case hashrateBelowThreshold = "hashrate_below_threshold"
            case hashrateCalculated = "hashrate_calculated"
            case lastSubmit = "last_submit"
            case secondSinceSubmit = "second_since_submit"
            case worker
        }
    }
    
    // usage examples:
    
    let ticker = try JSONDecoder().decode(Ticker.self, from: data)
    let workerKeys = ticker.workers.keys // "10003", "100151", "100205"
    let workers = ticker.workers.values  // all workers objects
    
    let alive = workers.filter { $0.alive } // all workers where alive==true
    let totalHashrate = alive.reduce(0.0) { $0 + $1.hashrateCalculated }
    
    0 讨论(0)
提交回复
热议问题