/ / API Bittrex - JSON Struct no Swift - json, swift, struct

API do Bittrex - JSON Struct no Swift - json, swift, struct

Eu estou tentando chamar a API Bittrex no meu exemplo de aplicativo iOS.

Eu estou tentando ler o JSON daqui. https://bittrex.com/api/v1.1/public/getmarketsummaries

Mas estou recebendo este erro: Espera-se que decodifique o Array, mas encontre um dicionário. ", UnderlyingError: nil)

De acordo com o resultado da pesquisa do Google, o JSON Struct está incorreto.

Onde eu poderia ter cometido um erro?

Aqui está o meu JSON Struct;

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"
}
}

E aqui está o meu JSON Struct;

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()

Respostas:

1 para resposta № 1

Eu encontrei meu próprio erro. Eu leio MarketSummaries como matriz ao ler dados do JSON. Mas não é uma matriz.

Linha ruim:

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

Linha corrigida

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

0 para resposta № 2

Você pode usar essa classe Result para recuperar seus dados do Json ... Acho que isso ajudará você.

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
}

}