簡體   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