从Swift 3中的URL中提取JSON值返回":"表达

时间:2018-01-23 07:59:56

标签: ios json swift

我正在学习Swift,我遇到了从URL文件解析JSON文件的问题。

我试图调用posts字典并从中解析audio值。

let url = URL(string: "https://api.myjson.com/bins/91nzd")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
    guard let data = data, error == nil else { return }

    do {
        let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
        let posts = json["posts"] as? [String: Any] ?? [:]
        print(posts)
        let audios = posts["audio"] as? [String: Any] ?? [:]
        print(audios)
    } catch let error as NSError {
        print(error)
    }
}).resume()

这会返回:, :,我认为这是一个零表达式。它调用的JSON文件如下所示:

{
  "posts": [
    {
      "id": "1",
      "title": "title 1",
      "audio": "https://rss-example.com/episodes/871ae23d.mp3"
    },
    {
      "id": "2",
      "title": "title 2",
      "audio": "https://rss-example.com/episodes/352ae29d.mp3"
    } 
  ] 
} 

从我看过的教程中,这对我来说是正确的,但是你看到了错误吗?还是我误解了?

1 个答案:

答案 0 :(得分:1)

错误是帖子Array类型,请尝试:

    let url = URL(string: "https://api.myjson.com/bins/91nzd")
    URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
        guard let data = data, error == nil else { return }

        do {
            let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
            if let posts = json["posts"] as? Array {
                for (index, element) in posts.enumerate() {
                    let audios = element["audio"] as? [String: Any] ?? [:]     
                     print(audios)
                }
            } 
        } catch let error as NSError {
            print(error)
        }
    }).resume()