【发布时间】:2018-11-24 03:03:15
【问题描述】:
"collection_listings" = (
{
"body_html" = "";
"collection_id" = 57229082710;
"default_product_image" = "<null>";
handle = men;
image = {
"created_at" = "2018-05-02T01:34:16-04:00";
src = "https://cdn.shopify.com/s/files/1/2331/3377/collections/men.jpg?v=1525239256";
};
"published_at" = "2018-05-02T01:34:16-04:00";
"sort_order" = manual;
title = Men;
"updated_at" = "2018-05-02T08:01:58-04:00";
}
如何使用 swift 4 在模拟器中打印这些数据? 当我尝试打印这些数据时,我收到了这个错误:
typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "预期解码 Array 但发现一个 字典代替。”,基础错误:无))
这是我更新的代码:
导入 UIKit
结构产品:可解码 { 让 product_id : 字符串 让标题:字符串 让图像:字符串 }
类 ViewController: UIViewController,UICollectionViewDataSource { var products = 产品
@IBOutlet weak var productCell: UICollectionView!
override func viewDidLoad()
{
super.viewDidLoad()
productCell.dataSource = self
guard let url = URL(string: "https://psofttech-test.myshopify.com/admin/collection_listings.json") else { return }
var request = URLRequest(url: url)
request.httpMethod = "GET"
let session = URLSession.shared
session.dataTask(with: url) { (data, response, error) in
if error == nil
{
do
{
let json = try JSONSerialization.jsonObject(with: data!) as? [String: Any]
self.products = try JSONDecoder().decode([product].self, from: data!)
print(self.products, "dddd")
for info in self.products
{
self.productCell.reloadData()
}
}
catch
{
print(error)
}
}
}.resume()
print(products.self,"0000")
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return products.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "productCollection", for: indexPath) as! productCollectionViewCell
cell.proLBL.text = products[indexPath.row].title
return cell
}
}
【问题讨论】:
-
请给我们看看你用来解析这个json的代码
-
“应解码 Array
,但找到了字典。”您误解了 JSON 的结构。你的 Codable 课程是什么?你在哪里尝试解析它?