json - 从 Guidebox API 在 Swift 中解析 JSON 数据

标签 json swift parsing

我正在尝试使用 Guidebox 中的 Swift 解析 JSON 数据。数据示例如下:

 {
  "results": [
    {
      "id": 14673,
      "title": "The Golden Girls",
      "alternate_titles": [
        "Golden Palace"
      ],
      "container_show": 0,
      "first_aired": "1985-09-14",
      "imdb_id": "tt0088526",
      "tvdb": 71292,
      "themoviedb": 1678,
      "freebase": "\/m\/01fszq",
      "wikipedia_id": 217200,
      "tvrage": {
        "tvrage_id": 5820,
        "link": "http:\/\/www.tvrage.com\/shows\/id-5820"
      },
      "artwork_208x117": "http:\/\/static-api.guidebox.com\/120214\/thumbnails_small\/14673-9570342022-208x117-show-thumbnail.jpg",
      "artwork_304x171": "http:\/\/static-api.guidebox.com\/120214\/thumbnails_medium\/14673-3759246217-304x171-show-thumbnail.jpg",
      "artwork_448x252": "http:\/\/static-api.guidebox.com\/120214\/thumbnails_large\/14673-2249565586-448x252-show-thumbnail.jpg",
      "artwork_608x342": "http:\/\/static-api.guidebox.com\/120214\/thumbnails_xlarge\/14673-6064109057-608x342-show-thumbnail.jpg"
    }
  ],
  "total_results": 1,
  "development_api_key": "You are currently using a temporary development API key. This API key is for testing only. You have used 57 of 250 available calls. Please see the API docs (http:\/\/api.guidebox.com\/apidocs) for additional information or to generate a production API key."
}

对于我来说,使用数据的最简单方法似乎是将其转换为 [String: Any],因为我真正需要的只是“id”、“title”和艺术品值。但是,我使用的所有(无数)方法都失败了,因为“alternate_titles”被解析为 NSArray,这让一切变得更加困难。 到目前为止,我已经尝试了这种方法的变体:

        do {
        let jsonResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: Any]
        let datafinal = jsonResult["results"] as! [String: Any]
//Fails around here usually, when the data is converted to [String: Any] or [Any:Any] because of the array.
        let title = datafinal["title"]
        } catch {
            print("JSON Preocessing failed")
        }

我还使用 SwiftyJSON 库尝试将数据转换为更易于阅读的 JSON,但是从中提取字典的方法总是失败(我猜也是由于结构)。谁有从 URL 中获取 JSON 数据并轻松访问“结果”中的值的简单方法?非常感谢任何帮助!

最佳答案

试试这个

 do {
     let jsonResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: Any]
     let datafinal = jsonResult["results"] as! NSArary

     let title = datafinal[0].value(forKey: "title")
    print("\(title)")
      } catch {
          print("JSON Preocessing failed")
      }

关于json - 从 Guidebox API 在 Swift 中解析 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41376701/

相关文章:

c# - 具有最小长度的 JSON 模式,除非为空/空

javascript - 使用 JSON 将 Javascript 对象发送到 Python Flask 时出错

java - 使用 Apache TIKA 解析文本时如何指定编码?

javascript - 我在网上找到这个 "[\\?&]v=([^&#]*)"谁能给我解释一下

JavaScript 从服务器解析 JSON

json - 重新部署到不同区域时出现 Azure 错误

swift - 在 ios 8 中使用蓝牙发送到外设的数据量

ios - 如何在 Swift 中将触摸事件发送到 nextResponder

ios - 如何在两点之间画一条线

java - 哪个面向 Java 的词法分析器用于简单项目(ANTLR、DIY 等)