swift json帮助在表视图控制器上显示数据

问题描述 投票:-1回答:1
// my  url
   //  https://fetch-hiring.s3.amazonaws.com/hiring.json
    /*
    my json 
    [
    {"id": 383, "listId": 4, "name": ""},
    {"id": 472, "listId": 1, "name": ""},
    {"id": 625, "listId": 2, "name": null}
    ]
   */
// my main vc class for table view controller 

import UIKit
class HeadlLinesTableViewController: UITableViewController {
      var parse = [HiringElement]()

    override func viewDidLoad() {

        // Do any additional setup after loading the view.


        super.viewDidLoad()
        // Do any additional setup after loading the view.
        let urlString =  "https://fetch-hiring.s3.amazonaws.com/hiring.json"
        guard let url = URL(string: urlString) else { return }

        // 2
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print(error!.localizedDescription)
            }

            guard let data = data else { return }
            // 3
            //Decode data

            self.Elements = try? JSONDecoder().decode(HiringElement.self, from: data)

            print(data)

            // 4
            //Get back to the main queue
            DispatchQueue.main.async  {
                self.tableView.reloadData()
            }
            // 5
            }.resume() // fires of request

    }

我的API的模型结构,这是我从quickTypeIo api生成器中使用的东西

struct HiringElement: Codable {
    let id, listID: Int
    let name: String?

    enum CodingKeys: String, CodingKey {
        case id
        case listID
        case name
    }
} typealias Hiring = [HiringElement]

而且我的表视图控制器方法在这里我无法显示数据,并且有些错误。我正在使用tableview控制器,所以不需要tableview委托或数据源

 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        guard let articles = Elements else { return 0 }

        return   return parse.count

    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

            as? newsTableViewCell else {
              fatalError(" cell not found ")  }

        // here I have errors thanks 

           cell.titleLabel.text = parse[indexPath.row].name
    print(cell.titleLabel.text)


        return cell
    }

}

这是我的表格视图单元格类

import UIKit

class newsTableViewCell: UITableViewCell {
    //var article:Article!
    @IBOutlet weak var avator: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var newsLabel: UILabel!



    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

    }


}
json swift xcode tableview codable
1个回答
0
投票

我认为您应该在解码部分上工作。这是一个解决方案:

struct HiringElement: Decodable {
    let id, listId: Int
    let name: String?
}

@propertyWrapper
struct IgnoreFailure<Value: Decodable>: Decodable {
    var wrappedValue: [Value] = []

    private struct _None: Decodable {}

    init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        while !container.isAtEnd {
            if let decoded = try? container.decode(Value.self) {
                wrappedValue.append(decoded)
            }
            else {
                try? container.decode(_None.self)
            }
        }
    }
}

然后在HeadlLinesTableViewController.swift中编写以下代码。

typealias ArrayIgnoringFailure<Value: Decodable> = IgnoreFailure<Value>

然后尝试将解码为:

guard let objects =  try? JSONDecoder().decode(ArrayIgnoringFailure<HiringElement>.self, from: data)  else { return }
self.elements = objects.wrappedValue

希望它将解决您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.