Swift 2解析JSON-无法下标'AnyObject'类型的值 [英] Swift 2 Parsing JSON - Cannot subscript a value of type 'AnyObject'

查看:140
本文介绍了Swift 2解析JSON-无法下标'AnyObject'类型的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了以下示例来解析JSON文件(例如,此处发布的另一个问题的答案: https://stackoverflow .com/a/27206145/4040201 ),但无法正常运行.我现在在"let ... = item ["..."] as?String"行上收到错误无法下标'AnyObject'类型的值"的错误.

I've tried following examples for parsing a JSON file (for example an answer to another question posted here: https://stackoverflow.com/a/27206145/4040201) but can't get it to work. I'm now getting the error "Cannot subscript a value of type 'AnyObject'" on the "let ... = item["..."] as? String" lines.

func connectionDidFinishLoading(connection: NSURLConnection) {

    do {
        let jsonResult = try NSJSONSerialization.JSONObjectWithData(self.bytes!, options: NSJSONReadingOptions.MutableContainers) as! Dictionary<String, AnyObject>

        if let searchResults = jsonResult["Search"] as? [AnyObject] {
            for item in searchResults {
                let title = item["Title"] as? String //Error Here
                let type = item["Type"] as? String //Error Here
                let year = item["Year"] as? String //Error Here

                print("Title: \(title) Type: \(type) Year: \(year)")
            }
        }

    } catch let error as NSError {
        NSLog("JSON Error: \(error)")
    }
}

JSON示例:

{ "Search": [
    {
    "Title":"Example 1",
    "Year":"2001",
    "Type":"Type1"
    },
    {
    "Title":"Example 2",
    "Year":"2006",
    "Type":"Type1"
    },
    {
    "Title":"Example 3",
    "Year":"1955",
    "Type":"Type1"
    }
]}

推荐答案

尝试一下

func connectionDidFinishLoading(connection: NSURLConnection) {

    do {
        let jsonResult = try NSJSONSerialization.JSONObjectWithData(self.bytes!, options: NSJSONReadingOptions.MutableContainers) as! Dictionary<String, AnyObject>

        if let searchResults = jsonResult["Search"] as? [[String: AnyObject]] {
            for item in searchResults {
                let title = item["Title"]
                let type = item["Type"]
                let year = item["Year"]

                print("Title: \(title) Type: \(type) Year: \(year)")
            }
        }

    } catch let error as NSError {
        NSLog("JSON Error: \(error)")
    }
}

这篇关于Swift 2解析JSON-无法下标'AnyObject'类型的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆