【问题标题】:Bittrex API - JSON Struct in SwiftBittrex API - Swift 中的 JSON 结构
【发布时间】:2017-10-08 21:41:54
【问题描述】:

我正在尝试在我的示例 iOS 应用程序中调用 Bittrex api。

我正在尝试从这里读取 JSON。 https://bittrex.com/api/v1.1/public/getmarketsummaries

但我收到此错误:应解码 Array 但找到了字典。”,underlyingError: nil)

根据谷歌搜索结果,JSON Struct 不正确。

我可能在哪里犯了错误?

这是我的 JSON 结构;

struct MarketSummaries : Decodable{
    let success : Bool?
    let message : String?
    let result : [SummaryResult]?
}

struct SummaryResult : Decodable{
    let marketName : String?
    let high : Double?
    let low : Double?
    let volume : Double?
    let last : Double?
    let baseVolume : Double?
    let timeStamp : String?
    let bid : Double?
    let ask : Double?
    let openBuyOrders : Int?
    let openSellOrders : Int?
    let prevDay : Double?
    let created : String?

    private enum CodingKeys : String, CodingKey {
        case marketName = "MarketName", high = "High", low = "Low", volume = "Volume",
        last = "Last", baseVolume = "BaseVolume", timeStamp = "TimeStamp", bid = "Bid",
        ask = "Ask", openBuyOrders = "OpenBuyOrders", openSellOrders = "OpenSellOrders",
        prevDay = "PrevDay", created = "Created"
    }
}

这是我的 JSON 结构;

let url = URL(string: "https://bittrex.com/api/v1.1/public/getmarketsummaries")
let session = URLSession.shared
let task = session.dataTask(with: url!) { (data, response, error) in
    if error != nil {}
    else
    {
        if (data != nil)
        {
            do
            {
                let coins = try JSONDecoder().decode([MarketSummaries].self, from: data!)

                DispatchQueue.main.async {
                    self.market = coins
                    self.table.reloadData()
                }
            }
            catch
            {
                print(error)
            }
        }
    }
}
task.resume()

【问题讨论】:

    标签: json swift struct


    【解决方案1】:

    我发现了自己的错误。从 JSON 读取数据时,我像数组一样读取 MarketSummaries。但它不是一个数组。

    坏线:

     let coins = try JSONDecoder().decode([MarketSummaries].self, from: data!)
    

    修正线

     let coins = try JSONDecoder().decode(MarketSummaries.self, from: data!)
    

    【讨论】:

      【解决方案2】:

      您可以使用这个 Result 类来检索您的 Json 数据...我认为这会对您有所帮助。

      import foundation
      
      public class Result {
      public var marketName : String?
      public var high : Double?
      public var low : Double?
      public var volume : Double?
      public var last : Double?
      public var baseVolume : Double?
      public var timeStamp : String?
      public var bid : Double?
      public var ask : Double?
      public var openBuyOrders : Int?
      public var openSellOrders : Int?
      public var prevDay : Double?
      public var created : String?
      
      /** Returns an array of models based on given dictionary.
      
      Sample usage:
      let result_list = Result.modelsFromDictionaryArray(someDictionaryArrayFromJSON)
      
      - parameter array:  NSArray from JSON dictionary.
      
      - returns: Array of Result Instances.
       */
      public class func modelsFromDictionaryArray(array:NSArray) -> [Result]
      {
          var models:[Result] = []
          for item in array
          {
              models.append(Result(dictionary: item as! NSDictionary)!)
          }
          return models
      }
      
       /**
       Constructs the object based on the given dictionary.
      
      Sample usage:
      let result = Result(someDictionaryFromJSON)
      
      - parameter dictionary:  NSDictionary from JSON.
      
      - returns: Result Instance.
      */
        required public init?(dictionary: NSDictionary) {
      
          marketName = dictionary["MarketName"] as? String
          high = dictionary["High"] as? Double
          low = dictionary["Low"] as? Double
          volume = dictionary["Volume"] as? Double
          last = dictionary["Last"] as? Double
          baseVolume = dictionary["BaseVolume"] as? Double
          timeStamp = dictionary["TimeStamp"] as? String
          bid = dictionary["Bid"] as? Double
          ask = dictionary["Ask"] as? Double
          openBuyOrders = dictionary["OpenBuyOrders"] as? Int
          openSellOrders = dictionary["OpenSellOrders"] as? Int
          prevDay = dictionary["PrevDay"] as? Double
          created = dictionary["Created"] as? String
      }
      
      
      /**
      Returns the dictionary representation for the current instance.
      
      - returns: NSDictionary.
       */
         public func dictionaryRepresentation() -> NSDictionary {
      
          let dictionary = NSMutableDictionary()
      
          dictionary.setValue(self.marketName, forKey: "MarketName")
          dictionary.setValue(self.high, forKey: "High")
          dictionary.setValue(self.low, forKey: "Low")
          dictionary.setValue(self.volume, forKey: "Volume")
          dictionary.setValue(self.last, forKey: "Last")
          dictionary.setValue(self.baseVolume, forKey: "BaseVolume")
          dictionary.setValue(self.timeStamp, forKey: "TimeStamp")
          dictionary.setValue(self.bid, forKey: "Bid")
          dictionary.setValue(self.ask, forKey: "Ask")
          dictionary.setValue(self.openBuyOrders, forKey: "OpenBuyOrders")
          dictionary.setValue(self.openSellOrders, forKey: "OpenSellOrders")
          dictionary.setValue(self.prevDay, forKey: "PrevDay")
          dictionary.setValue(self.created, forKey: "Created")
      
          return dictionary
      }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2018-05-29
        • 2018-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-11
        • 2017-12-16
        • 2017-11-20
        • 1970-01-01
        相关资源
        最近更新 更多