Expected to decode Array but found a dictionary instead

前端 未结 1 702
囚心锁ツ
囚心锁ツ 2020-12-05 16:43

I was fetching data from an API returning an array but needed to replace it by an API that has \"sub levels\":

RAW:
    ETH:
        USD:
             TYPE:          


        
相关标签:
1条回答
  • 2020-12-05 16:50

    First of all the JSON does not contain any array. It's very very easy to read JSON. There are only 2 (two!) collection types, array [] and dictionary {}. As you can see there are no square brackets at all in the JSON string.

    Any (sub)dictionary {} has to be decoded to its own type, so it's supposed to be

    struct Root : Decodable {
        private enum CodingKeys : String, CodingKey { case raw = "RAW" }
        let raw : RAW
    }
    
    struct RAW : Decodable {
        private enum CodingKeys : String, CodingKey { case eth = "ETH" }
        let eth : ETH
    }
    
    struct ETH : Decodable {
        private enum CodingKeys : String, CodingKey { case usd = "USD" }
        let usd : USD
    }
    
    struct USD : Decodable {
    
        private enum CodingKeys : String, CodingKey {
            case type = "TYPE"
            case market = "MARKET"
            case price = "PRICE"
            case percentChange24h = "CHANGEPCT24HOUR"
        }
        let type : String
        let market : String
        let price : Double
        let percentChange24h : Double
    }
    

    To decode the JSON and and print percentChange24h you have to write

     let result = try JSONDecoder().decode(Root.self, from: data)
     print("percentChange24h", result.raw.eth.usd.percentChange24h)
    
    0 讨论(0)
提交回复
热议问题