ios - swift:将 alamofire 中的 JSON 数据解析为带有数组的字典

标签 ios json swift api alamofire

我有以下 JSON 响应,我想获取命中对象的 id

{
    "totalHits":500,
    "hits":[
        {
            "largeImageURL":"https://pixabay.com/get/ea32b90a2af3073ed1584d05fb1d4190e070e4d71aac104491f1c270a0eeb7b0_1280.jpg",
            "webformatHeight":426,
            "webformatWidth":640,
            "likes":0,
            "imageWidth":4494,
            "id":3785276,
            "user_id":10546560,
            "views":21,
            "comments":0,
            "pageURL":"https://pixabay.com/en/port-river-liner-sea-cruise-3785276/",
            "imageHeight":2996,
            "webformatURL":"https://pixabay.com/get/ea32b90a2af3073ed1584d05fb1d4190e070e4d71aac104491f1c270a0eeb7b0_640.jpg",
            "type":"photo",
            "previewHeight":99,
            "tags":"port, river, liner",
            "downloads":9,
            "user":"LunevAndrey",
            "favorites":0,
            "imageSize":3306757,
            "previewWidth":150,
            "userImageURL":"",
            "previewURL":"https://cdn.pixabay.com/photo/2018/10/31/06/55/port-3785276_150.jpg"
        }
   ]
}

这就是我目前所拥有的,

import UIKit
import SDWebImage

class Model: NSObject {
    var title : Any!

    init (dict :  [String:Any]) {
        self.title = (((dict as AnyObject)["hits"] as! [String:AnyObject])) ["id"] as? Any


    }
}

在 View Controller 中,我的编码如下。

import UIKit
import Alamofire



class CollectionView: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {

    let url1 = ["URL path string"]
    @IBOutlet weak var collection: UICollectionView!
    var arrList = [Model]()


    override func viewDidLoad() {
        super.viewDidLoad()
        reequest()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        self.collection.reloadData()

    }

        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
           return arrList.count

        }

        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

            let cell: firstCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! firstCollectionViewCell
            let objct = arrList[indexPath.row]
            cell.label.text =  objct.title as AnyObject as? String

            return cell
        }

        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

             let width = (self.view.frame.size.width - 5  * 3 ) / 2 //some width
             let height = width * 1.34 //ratio
            return CGSize(width: width, height: height)
        }


    func reequest() {

        let url = URL(string: "URL path string")
        Alamofire.request(url!).responseJSON {(response) in
         switch (response.result){
            case .success:
                if let data = response.result.value{
                    if let arrdata = data as? [[String:Any]]{

                        for dataList in arrdata {
                            print(dataList)
                            let obj = Model(dict: dataList)
                            self.arrList.append(obj)
                            self.collection.reloadData()
                        }
                    }
                }
            case .failure(let error):
                print("error to print the data \(error)")
            }
        }
    }
}

最佳答案

Codable 的 易于使用,在这种情况下应该是最佳选择。下面是根据响应完全重写的模型,

class HitItem: Codable {
    var id : Int
    var user: String
}

class HitsResponse: Codable {
    var totalHits: Int
    var hits: [HitItem]
}

class CollectionView: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {

    let url1 = ["URL path string"]
    @IBOutlet weak var collection: UICollectionView!
    var arrList = [HitItem]()


    override func viewDidLoad() {
        super.viewDidLoad()
        reequest()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        self.collection.reloadData()

    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return arrList.count

    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell: firstCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! firstCollectionViewCell
        let objct = arrList[indexPath.row]
        cell.label.text =  String(objct.id)

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        let width = (self.view.frame.size.width - 5  * 3 ) / 2 //some width
        let height = width * 1.34 //ratio
        return CGSize(width: width, height: height)
    }


    func reequest() {

        let url = URL(string: "URL path string")
        Alamofire.request(url!).responseJSON {(response) in
            switch (response.result){
            case .success:
                if let data = response.data {
                    do {
                        let response = try JSONDecoder().decode(HitsResponse.self, from: data)
                        self.arrList = response.hits
                        self.collection.reloadData()
                    } catch {
                        print(error.localizedDescription)
                    }
                }
            case .failure(let error):
                print("error to print the data \(error)")
            }
        }
    }
}

关于ios - swift:将 alamofire 中的 JSON 数据解析为带有数组的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53149004/

相关文章:

iphone - xcode 7 tableviewcontroller中的多个pickerview

ios - 我的测试目标中没有这样的模块 'XXX'

ios - 如何检测 iPhone 6s 和 6s+

ios - 连接wifi时获取ios设备的IP地址

c# - 在 ASP.NET C# 中反序列化 JSON

javascript - 如何使用Vue过滤结果 "live"?

ios - 计算Xib文件的高度

ios - 从数组 swift 访问图像

java - 默认类多态性 Jackson Java

arrays - 从 Swift 中的字典中的数组访问项目