我收到以下错误:
Error serialising json typeMismatch(Swift.Dictionary, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary but found an array instead.", underlyingError: nil))
代码:
//---------------
struct Currency: Decodable {
let symbol: String
let price: String
}
var myDict: [Currency] = []
//---------------
func testParse(){
let jsonUrlString = "https://api.binance.com/api/v3/ticker/price"
guard let url = URL(string: jsonUrlString) else
{ return }
URLSession.shared.dataTask(with: url) { (data,response,err) in
guard let data = data else
{
print("Error: No data to decode")
return
}
do
{
let exchanges = try
JSONDecoder().decode(Currency.self, from: data)
let X: [Currency] = [exchanges]
self.myDict = X
self.testFunc()
print("binance: "+self.myDict[0].symbol + ": "+self.myDict[0].price)
}
catch let jsonErr
{
print("Error serialising json",jsonErr)
}
}
.resume()
}
我的结构布局有问题吗?还是我正在解析的方式?我想在这里得到更好的理解,以备将来引用。因此,如果有人可以链接一个好的 Swift 4 指南,我们将不胜感激。或者,如果您能给我一个详细的答案,那就太好了(而不是在我不了解的地方用勺子填满答案)。
最佳答案
请仔细阅读错误信息并学会理解。非常清楚。
Expected to decode Dictionary but found an array instead
换句话说:您想要解码字典 (Currency
) 但实际上它是一个数组 ([Currency]
)。
在 Decodable
方面,字典 是目标结构或类。
请不要将对象命名为 ...dict
,它实际上是一个数组。
var myArray = [Currency]()
...
let exchanges = try JSONDecoder().decode([Currency].self, from: data)
self.myArray = exchanges
关于json - 使用 Swift 可解码解析 JSON 字典时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50131567/