我正在开发Swift 4并且目前正在使用Walmart的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()
}
}
答案 0 :(得分:2)
就像这样,
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)
答案 1 :(得分:1)
你的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)