在swift 4中解析json时出错

时间:2017-11-29 16:00:05

标签: json swift

我想在我的应用中使用JSON从网站获取数据。但问题是,当我尝试在JSON数据中获取密钥[" posts"]的值时,会出现错误。

let url = NSURL(string: "http://bongdavn.com/category/du-lieu/?json=1")!
let request = NSMutableURLRequest(url: url as URL)
URLSession.shared.dataTask(with: request as URLRequest) { (data : Data?, urlResponse : URLResponse?, error : Error?) in
    if error != nil {
    }

    do {
        let json = try JSONSerialization.jsonObject(with: data!) as? [String : Any]
        let post = json!["post"] as! [String : Any]
        print(post)
        let content = post["content"] // error show from here.

        print(content)
        // the compiler show nil instead of value of "content"

        DispatchQueue.main.async {
            self.TableView.reloadData()
        }
    }
    catch {
        print("Catch the error : \(error)")
    }
}
.resume()

这是我的json数据:

{  
   "status":"ok",
   "post":{  
      "id":121,
      "type":"post",
      "slug":"epl-england-premier-league-anh",
      "url":"http:\/\/bongdavn.com\/epl-england-premier-league-anh\/",
      "status":"publish",
      "title":"[EPL] England Premier League – Anh",
      "title_plain":"[EPL] England Premier League – Anh",
      "content":"<p>West Ham <strong><span class=\"hom\">1<\/span>\u00a0&#8211;\u00a0<\/strong><span class=\"awy\"><strong>1<\/strong>\u00a0<\/span>Leicester|||Crystal Palace\u00a0<strong><span class=\"hom\">2<\/span>\u00a0&#8211;\u00a0<\/strong><span class=\"awy\"><strong>1<\/strong>\u00a0<\/span>Stoke|||,
      "date":"2017-11-29 09:44:13",
      "modified":"2017-11-29 09:44:16",
      "categories":[  ],
      "tags":[  ],
      "author":{  },
      "comments":[  ],
      "attachments":[  ],
      "comment_count":0,
      "comment_status":"open",
      "custom_fields":{  }
   },
   "previous_url":"http:\/\/bongdavn.com\/bundesliga-dortmund-schalke\/"
}

这是错误:

  

无法转换类型&#39; __ NSSingleObjectArrayI&#39;的值(0x109b9c328)到&#39; NSDictionary&#39; (0x109b9cf58)。   2017-11-29 22:45:19.764169 + 0700 BongDa [713:17684]无法转换类型&#39; __ NSSingleObjectArrayI&#39; (0x109b9c328)到&#39; NSDictionary&#39; (0x109b9cf58)。   (lldb)

1 个答案:

答案 0 :(得分:1)

你发布的json是错误的,根据我从网址得到的内容,有一个数组posts,所以你可以这样做:

do {
    let json = try JSONSerialization.jsonObject(with: data!) as? [String : Any]
    let posts = json!["posts"] as! [[String: Any]] // posts is an array
    let post = posts.first! // get the first here, or according to your need
    print(post)
    let content = post["content"]
    print(content)

    DispatchQueue.main.async {
        self.TableView.reloadData()
    }
}
catch {
    print("Catch the error : \(error)")
}
}
.resume()