Я разрабатываю Swift 4 и в настоящее время использую API Walmart для отображения своих продуктов и определенной информации о продуктах (например: название продукта, цена продукта). Я прочитал и просмотрел множество руководств по анализу данных JSON, однако продолжаю получать ту же ошибку. Если бы кто-нибудь мог сказать мне, почему я получаю сообщение об ошибке, я был бы очень признателен, увидев, что я застрял в этой проблеме на несколько дней.
Вот данные JSON, которые я получаю от вызова API:
{
query: "ipod",
sort: "relevance",
format: "json",
responseGroup: "base",
totalResults: 3570,
start: 1,
numItems: 10,
items: [
{
itemId: 15076191,
parentItemId: 15076191,
name: "Apple iPod Touch 4th Generation 32GB with Bonus Accessory Kit",
salePrice: 189
}
Я просто хочу отобразить данные name
и salePrice
, но в данный момент я не могу этого сделать, вместо этого я получаю эту ошибку: typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))
Вот моя модель данных:
struct Product: Codable {
let name: String
let salePrice: String
}
Вот код в моем классе ViewController:
class ViewController: UIViewController {
import Foundation
import UIKit
var products: [Product]?
override func viewDidLoad() {
super.viewDidLoad()
let urlString = "https://api.walmartlabs.com/v1/search?query=sauce&format=json&apiKey=xyz"
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!.localizedDescription)
}
guard let data = data else { return }
//Implement JSON decoding and parsing
do {
//Decode retrived data with JSONDecoder and assing type of Article object
let productData = try JSONDecoder().decode([Product].self, from: data)
print(productData)
} catch let jsonError {
print(jsonError)
}
}.resume()
}
}