【问题标题】:How to display nested JSON array element in View controller如何在视图控制器中显示嵌套的 JSON 数组元素
【发布时间】:2021-09-11 07:22:08
【问题描述】:

当我尝试在 tableview 单元格中显示作者姓名时,我收到错误,例如“无法将 [String] 类型的值分配给 String 类型”,因为我将作者元素声明为数组。由于作者元素的API响应是一个数组,我不知道如何声明它。请帮助我

API 响应

{
  "kind": "books#volumes",
  "totalItems": 2361,
  "items": [
    {
      "kind": "books#volume",
      "id": "_eyJAAAAQBAJ",
      "etag": "MJbx6HKC3B4",
      "volumeInfo": {
        "title": "A Quilting Life",
        "subtitle": "Creating a Handmade Home",
        **"authors": [
          "Sherri McConnell"
        ],**
        "publisher": "C&T Publishing Inc",
        "publishedDate": "2013-02-12",

struct VolumeInfo : Codable {
    
    let authors : [String]
    let publisher : String?
    let subtitle : String?
    let title : String?

}

代码:

class MainVC: UIViewController,UITableViewDelegate,UITableViewDataSource {
   
    var items : [Items] = []
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
       
        self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.jpeg")!)
        fetchBooks { data in
            self.items.self = data
            DispatchQueue.main.async {
                self.bookTableView.reloadData()
            }
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = tableView.dequeueReusableCell(withIdentifier: "BookCell",for:indexPath) as! BookCell
        cell.bookAuthor.text = items[indexPath.row].volumeInfo.title
        cell.bookCategory.text = items[indexPath.row].volumeInfo.publisher
        cell.bookAuthor.text = items[indexPath.row].volumeInfo.authors
        return cell
    }
    
    func fetchBooks(comp : @escaping ([Items])->()){
        
        let urlString = "https://www.googleapis.com/books/v1/volumes?q=quilting"
        let url = URL(string: urlString)
         
         guard url != nil else {
             return
         }
         let session = URLSession.shared
         
         let dataTask = session.dataTask(with: url!) { [self] (data, response, error) in
             //check for errors
             if error == nil && data != nil{
           
                 //parse json
                 
                 do {
                     let result = try JSONDecoder().decode(Book.self, from: data!)
                    comp(result.items)
                    
                     print("Retrieved books are \(items)")
                 }
                 catch {
                     print("Error in json parcing\(error)")
                 }
             }
         }
         //make api call
         dataTask.resume()
         
    }
}
  

【问题讨论】:

  • 一个叫“书”的人从何而来?

标签: ios json swift parsing codable


【解决方案1】:

text 需要一个字符串,authors 是一个字符串数组。这是错误明确指出的类型不匹配。

解决办法是join数组

cell.bookAuthor.text = items[indexPath.row].volumeInfo.authors.joined(separator: ", ")

旁注:

一次又一次地获得相同的价值是不必要的昂贵。更好的方法是

let info = items[indexPath.row].volumeInfo
cell.bookAuthor.text = info.title
cell.bookCategory.text = info.publisher
cell.bookAuthor.text = info.authors.joined(separator: ", ")

【讨论】:

    猜你喜欢
    • 2021-07-01
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 2016-10-20
    • 2018-10-31
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    相关资源
    最近更新 更多