获取数据(类型不匹配)WEBAPI时出现SwiftUI URLSession错误

获取数据(类型不匹配)WEBAPI时出现SwiftUI URLSession错误,swiftui,xcode11,swift5,type-mismatch,urlsession,Swiftui,Xcode11,Swift5,Type Mismatch,Urlsession,我试着从一个url获取数据,一旦我按下了一个按钮并调用了这个函数,但是一旦调用了这个函数,我就一直得到一个类型不匹配的错误 这是我的代码: struct User: Decodable { var symbol: String var price: Double } struct Response: Decodable { var results:[User] } struct ContentView: View { var body: some View

我试着从一个url获取数据,一旦我按下了一个按钮并调用了这个函数,但是一旦调用了这个函数,我就一直得到一个类型不匹配的错误

这是我的代码:

struct User: Decodable {
    var symbol: String
    var price: Double
}

struct Response: Decodable {
    var results:[User]
}


struct ContentView: View {
    var body: some View {
        VStack {
            Text("hello")
            Button(action: {
                self.fetchUsers(amount: 0)
            }) {
                Text("Button")
            }
        }

    }

    func fetchUsers(amount: Int) {
        let url:URL = URL(string: "https://api.binance.com/api/v3/ticker/price")!

        URLSession.shared.dataTask(with: url) { (data, res, err) in
            if let err = err { print(err) }
            guard let data = data else { return }
            do {
                let response = try JSONDecoder().decode(Response.self, from: data)
                print(response.results[0])
            } catch let err {
                print(err)
            }
        }.resume()
    }

}
这就是错误:

typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))
类型不匹配(Swift.Dictionary,Swift.DecodingError.Context(codingPath:[],debugDescription:“应解码字典,但找到了一个数组。”,underlineerror:nil))
我试图从中获取数据的网站url为:

我试图从一个特定的符号获取一个特定的价格,例如ETHBTC的价格,即0.019


谢谢

这种方法有两个错误。首先,如果您使用

results = [User]
typealias Response = [User]
通过这种方式,您希望json的格式为[result:{}],但您的[{}]格式在开头没有名称。因此,您应该将响应结构替换为

results = [User]
typealias Response = [User]
您使用的第二个API是返回字符串而不是作为价格的double,因此您应该将结构修改为:

struct User: Decodable {
    var symbol: String
    var price: String
}
这样对我来说很有效。测试

  • 斯威夫特5
  • 代码11.3.1
  • iOS 13.3.1非测试版