类型'Any'没有下标成员

时间:2016-10-03 21:57:39

标签: swift

我已经为swift2.2工作json解析代码但是当我使用Swift 3.0时我得到错误(Type'Any'没有下标成员),任何人都可以帮我转换代码。

do {        
                let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)

                if json is [String: AnyObject] {
                    print(json)

                    if let error = json["error"] as? String {
                        print(error);
                    } else if let items = json["items"] as? [[String: AnyObject]] {

                        for item in items {
                            print(item)

                            let book_id = item["id"] as? String

                            if let volumeInfo = item["volumeInfo"] as? [String: AnyObject] {
                                let book_title = volumeInfo["title"] as? String
                                DispatchQueue.main.async(execute: { () -> Void in
                                    self.lblDataInfo.text = "ISBN: "+self.currentISBN!+"  ID:"+book_id!
                                    self.lblDataType.text = book_title
                                })
                            }

                            break // for now, only show first
                        }

                    } else {
                        DispatchQueue.main.async(execute: { () -> Void in
                            self.lblDataInfo.text = "ISBN: "+self.currentISBN!+"  Not identified"
                            self.lblDataType.text = ""
                        })
                    }
                }

            } catch let jsonError {
                print(jsonError)
            }

            }
            task.resume()

        }
}

2 个答案:

答案 0 :(得分:0)

这个:if json is [String: AnyObject] {正在检查json是否是字典,但是没有将其转换为字典,所以当你尝试在这里以字典形式访问它时:json["error"]你&#39 ;尝试以字典形式访问它。

相反,您只需要将其转换为具有正确类型的新变量:

if let jsonDictionary = json as? [String : AnyObject] {

答案 1 :(得分:-1)

似乎json数据通过,但它不知道数据的类型,因为截至目前它的类型为Any

if json is [String: AnyObject] {
                print(json)
let jsonData = json as! NSDictionary // or if you want to be more specific ,'json as! [String: AnyObject]' but u will have to cast the value of your dict 'AnyObject' later on

现在,数据不是'Any'类型,而是'NSDictionary'类型

如果你想测试它,你可以在print(json)行之前放置一个断点,在运行代码后,在po json as! NSDictionary的控制台类型中,这样你就可以看到NSDictionary是否是正确的类型转换你的json数据

相关问题