【问题标题】:How to parse jsondata using API in swift 4如何在 swift 4 中使用 API 解析 jsondata
【发布时间】: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 课程是什么?你在哪里尝试解析它?

标签: ios json iphone swift


【解决方案1】:

看看这段代码对你有没有帮助..

if let data = data as? [String: Any] {
        if let data = data["collection_listings"] as? NSArray {
            for data in data {
                if let data = data as [String: Any] {

                }
            }
        }
    }

【讨论】:

    【解决方案2】:

    现在你可以在 Swift 4.0 中使用 codable 解析 json 数据了。

    • 使用 Codable,我们可以将 JSONObject 或 PropertyList 文件建模成 通过编写非常少的代码行来实现等效的结构或类。我们 不必为中的属性编写构造函数 对象。这一切都由 Codable 提供。我们只需要扩展我们的模型 符合 Codable、Decodable 或 Encodable 协议。

    • Swift 的强数据类型和丢失数据类型不匹配 JSON 已由 Swift 编译器在内部处理。我们现在可以 处理 Swift 数据类型,如 Date、URL、Float 等

    • 复杂的 JSON 可以使用嵌套结构轻松建模 可读性。

    • 使用 JSONDecoder 解析实际 JSON 成为单线

    你可以参考这个应用程序使用编码:Demo App for Codable Swift

    【讨论】:

      【解决方案3】:

      您使用了错误的对象进行解码。基本上它告诉您发送给解码器的对象类型与 JSON 不匹配。在您的情况下(没有看到您的代码,很难准确判断)您提供的对象似乎是数组类型,而 JSON 是字典。这是我通常使用的方法:

      指定一个你想要解码的结构体:

      struct Response {
          var collection_listings: Listing
      }
      
      struct Listing {
          var collection_id: String
      }
      

      在您的解码器中具体如下:

      let decoder = JSONDecoder()
      let apiResponse = try decoder.decode(Response.self, from: data)
      

      【讨论】:

        猜你喜欢
        • 2019-09-01
        • 1970-01-01
        • 2019-02-12
        • 2018-02-13
        • 1970-01-01
        • 2018-09-05
        • 2019-01-02
        • 2018-10-21
        • 1970-01-01
        相关资源
        最近更新 更多