【发布时间】:2018-03-26 05:48:13
【问题描述】:
我正在使用 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()
}
}
【问题讨论】:
标签: ios json swift api codable