【问题标题】:How do I extract just the title and artist?如何仅提取标题和艺术家?
【发布时间】:2015-12-07 06:03:10
【问题描述】:

我正在尝试提取所有标题和艺术家。我目前可以获得包含所有条目的 JSON 页面,但无法仅提取标题和艺术家。下面是进入页面的代码。

 func getMeta(){

    let searchTerm = PFUser.currentUser?.username
    var endpoint = NSURL(string: "http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=\(searchTerm)&api_key=aa03f5bd00409f3bb5372c6ad0bc5655&format=json&callback=?")
    var data = NSData(contentsOfURL: endpoint!)

    let task = NSURLSession.sharedSession().dataTaskWithURL(endpoint!) {(data, response, error) -> Void in
        do {
            if let dict: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
            {
              if let items = dict["track"] as? NSArray {
                    for item in items {
                        let x =  (dict["track"]!["name"] as? String)!
                        print(x)
                    }
                }

            }

        } catch let jsonError as NSError {
        }
    }
    task.resume()
}

【问题讨论】:

  • 研究 Alamofire 和 SwiftyJSON。简单
  • 我做到了,这就是我走到这一步的原因。我仍然不熟悉它。我只是想弄清楚如何获取每个条目的标题和艺术家。

标签: json swift parsing


【解决方案1】:

您永远不应忽略错误消息。

catch 分支中添加print(jsonError),您将看到错误:您的JSON 无效。

为什么?因为在您的 URL 中,您使用的是 callback,它会在 JSON 字符串前面添加 JavaScript 字符。

从网址中删除&callback=?,网址应以&format=json结尾。

然后您必须正确遵循 JSON 类型:什么是字典、什么是数组、什么是键...并使用 if let 或任何其他已知方法安全地解开值:

do {
    if let jsonData = data,
        let dict = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as? NSDictionary,
        let recent = dict["recenttracks"] as? NSDictionary,
        let items = recent["track"] as? NSArray {
            for item in items {
                if let x = item["name"] as? String {
                    print(x)
                }
            }
    }
} catch let jsonError as NSError {
    print(jsonError)
}

【讨论】:

  • 我收到此错误Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
  • 我在回答中解释了如何修改 URL 以获得正确的 JSON。
【解决方案2】:

你为什么不试试 Alamofire?

Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
         .responseJSON { response in
             print(response.request)  // original URL request
             print(response.response) // URL response
             print(response.data)     // server data
             print(response.result)   // result of response serialization

             if let JSON = response.result.value {
                 print("JSON: \(JSON)")
             }
         }

【讨论】:

  • 我不熟悉 Alamofire,我觉得使用我的方法更舒服。
猜你喜欢
  • 2019-01-13
  • 2013-03-26
  • 2016-07-23
  • 2022-08-03
  • 1970-01-01
  • 2015-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多