繁体   English   中英

如何在 TableView Swift 中解析嵌套的 JSON 数组?

[英]How to parse nested JSON array in TableView Swift?

我正在使用一个返回 JSON 作为响应的端点。 问题是响应json对我来说是一个巨大的数据。 从那以后,我想显示所有要在 tableview 中显示的 Surah(englishName) 名称。 作为 iOS 开发的新手,我尽了最大的努力。 请看一下我的代码片段,让我知道我哪里做错了。

我的 Json 数据在这里:

视图控制器代码:

var surahName = [Surah]()

@IBOutlet weak var tableView: UITableView!

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


//MARK: JSON parse
func parseJSON()  {
    let url = URL(string: "https://api.alquran.cloud/v1/quran/ar.alafasy")
    
    guard url != nil else{
        print("URL Founr Nill")
        return
    }
    
    URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error == nil && data != nil{
            do{
                self.surahName = try JSONDecoder().decode([Surah].self, from: data!)

                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }catch{
                print(error)
            }
        }
    }.resume()
}

//MARK: Tableview delegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return surahName.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell:QuranAudioCell = tableView.dequeueReusableCell(withIdentifier: "cell") as! QuranAudioCell
    let arrdata = surahName[indexPath.section].data.surahs
    cell.nameLbl.text = arrdata[indexPath.row].englishName
    return cell
}

问题是它没有在 tablview 中打印任何东西。

将第一行更改为

var surahNames = [EnglishName]()

内部 do-catch 块更改

self.surahName = try JSONDecoder().decode([Surah].self, from: data!)

进入

let response = try JSONDecoder().decode(Surah.self, from: data!)
self.surahName = response.data.surahs

现在在 cellForRowAtIndexPath 里面做这个

let surah = surahName[indexPath.row]
cell.nameLbl.text = surah.englishName

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM