从 GoogleApiBooks 解析 JSON

Parse JSON from GoogleApiBooks

我正在尝试解析这个 JSON 但它不起作用。

这是JSON:

{
  "kind": "books#volumes",
  "totalItems": 1,
  "items": [
    {
      "kind": "books#volume",
      "id": "uCHmPQAACAAJ",
      "etag": "aBZ3KnoRsq4",
      "selfLink": "https://www.googleapis.com/books/v1/volumes/uCHmPQAACAAJ",
      "volumeInfo": {
        "title": "Psicologia delle folle",
        "authors": [
          "Gustave Le Bon"
        ],
        "publishedDate": "2004",
        "industryIdentifiers": [
          {
            "type": "ISBN_10",
            "identifier": "8850206240"
          },
          {
            "type": "ISBN_13",
            "identifier": "9788850206247"
          }
        ],
        "readingModes": {
          "text": false,
          "image": false
        },
        "pageCount": 251,
        "printType": "BOOK",
        "categories": [
          "Psychology"
        ],
        "maturityRating": "NOT_MATURE",
        "allowAnonLogging": false,
        "contentVersion": "preview-1.0.0",
        "language": "it",
      },
      "saleInfo": {
        "country": "IT",
        "saleability": "NOT_FOR_SALE",
        "isEbook": false
      },
      "accessInfo": {
        "country": "IT",
        "viewability": "NO_PAGES",
        "embeddable": false,
        "publicDomain": false,
        "textToSpeechPermission": "ALLOWED",
        "epub": {
          "isAvailable": false
        },
        "pdf": {
          "isAvailable": false
        },
        ,
        "accessViewStatus": "NONE",
        "quoteSharingAllowed": false
      }
    }
  ]
}

这是我正在使用的代码:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    var url = "https://www.googleapis.com/books/v1/volumes?q=isbn9788850206247&key=my-key"


    Alamofire.request(url).responseJSON { (responseData) -> Void in
        if((responseData.result.value) != nil) {
            let swiftyJsonVar = JSON(responseData.result.value!)

            if let resData = swiftyJsonVar["items"].arrayObject {
                self.arrRes = resData as! [[String:AnyObject]]
                print(self.arrRes)
            }
            if self.arrRes.count > 0 {
                self.tableProva.reloadData()
            }
        }
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableProva.dequeueReusableCell(withIdentifier: "cellProva", for: indexPath) as! CellProvaClass
    var dict = arrRes[indexPath.row]
    cell.titleLabel?.text = dict["title"] as? String
    cell.authorLabel?.text = dict["authors"] as? String
    return cell
}

我该如何解决这个问题?

当您在

行解析 JSON 时

if let resData = swiftyJsonVar["items"].arrayObject {

您将收到一个 object 的 NSDictionary,其中包含键中的所有其他嵌套元素和数组。在您的 tableView 委托中,您通过将其拆箱到 NSDictionary object 来直接访问 arrRes 中的值。所有条目都在名为 items 的数组中可用,该数组还有一个嵌套的 object volumeInfo,其中包含有关标题的信息和另一个数组 Authors.

您需要从 arrRes object 中提取更多嵌套的 object 以在您的 tableView cellForRowAtIndex 委托函数中使用它。

如果您需要任何进一步的帮助,请告诉我。

这是您的 JSON 回复(短格式):

这是数据结构(数组和字典格式):

现在您必须访问:titleauthors 所以这是您在 cellforRowAtIndexPath 方法中的值,一个名称为 dict 的字典存储 volumeInfo ( a Dictionary) 的值:

所以你必须使用这种方式来访问标题:

cell.titleLabel?.text = dict["volumeInfo"]["title"] as? String

//To Fetch Author array
  if let authorArray = dict["volumeInfo"]["authors"] as? NSArray{
          print(authorArray)
   }

然后访问 author 是一个数组,因此您要在 cell.authorLabel 中显示哪个索引值。

在第二张截图中,{} is Dictionary and [] is Array

首先尝试显示标题,然后以同样的方式尝试获取作者数组的值并根据您的要求进行设置。

如有任何其他问题,请随时发表评论。