我正在使用 Swift 4 进行开发,目前使用沃尔玛的 API 来显示他们的产品和有关产品的某些信息(例如:产品名称、产品价格)。我已经阅读并观看了许多有关解析 JSON 数据的教程,但是我仍然遇到相同的错误。如果有人能告诉我为什么会出现错误,我将不胜感激。
这是我从 API 调用中获取的 JSON 数据:
{
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 = "http://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()
}
}
会是这样的,
struct Item: Codable {
let query: String
let sort: String
let responseGroup: String
let totalResults: Int
let start: Int
let numItems: Int
let items: [Product]
}
struct Product: Codable {
let name: String
let salePrice: CGFloat
}
尝试使用这个,
let productData = try JSONDecoder().decode(Item.self, from: data)
您的 json 数据是字典而不是数组,您可以解析它并获取数组,或者尝试这个
struct Item: Codable {
let query: String
let sort: String
let format: String
let responseGroup: String
let totalResults: Int
let start: Int
let numItems: Int
let items: [Product]
}
struct Product: Codable {
let itemId: Double
let parentItemId: Double
let name: String
let salePrice: Int
}
let productData = try JSONDecoder().decode(Item.self, from: data)