我一直在获取JSON在我的视图控制器,我需要的功能,在同一VC以火力添加数据,所以进口火力地堡(豆荚火力核心,权威性和公司的FireStore),现在它给了我一个错误的JSON获取它的暧昧使用“标”的
func getDetails(link: URL!) {
var plot : String = " "
let task = URLSession.shared.dataTask(with: link!) { (data, response, error) in
if error != nil
{
print("error")
}
else
{
if let content = data
{
do
{
//JSON results
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableLeaves) as AnyObject
//myJson ~~~ ["Plot"] Ambiguous use of 'subscript'
plot = myJson["Plot"] as! String
}
catch
{
print("error in JSONSerialization")
}
}
}
}
task.resume()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
self.plot.text = plot
})
}
我很想保持挑JSON的“暗算”价值的能力,并有火力点运行
你的问题是铸造从JSONSerialization
结果AnyObject
。如果你希望能够使用下标,你应该在你的情况下,低垂的结果字典类型,例如[String:Any]
if let myJson = try JSONSerialization.jsonObject(with: content, options: .mutableLeaves) as? [String:Any] {
// plot = myJson["Plot"] as? String ?? "Default value"
}
不管怎么说,而学习一些关于Codable
,并用它来代替JSONSerialization
的。只要创建类/结构符合Decodable
协议,然后使用JSONDecoder
解码Data
对象。
以下是我将重写这个方法,因为它表示你的服务器响应ModelObject
结构或类。
func getDetails(link: URL!) {
var plot = " "
let group = DispatchGroup()
group.enter()
let task = URLSession.shared.dataTask(with: link!) { (data, response, error) in
defer { group.leave() }
guard error == nil else {
print(error)
return
}
if let content = data {
do {
let modelObject = try JSONDecoder().decode(ModelObject.self, from: data)
plot = modelObject.plotString
}
catch {
print(error)
}
}
}
task.resume()
group.notify(queue: DispatchQueue.main) {
self.plot.text = plot
}
}