【问题标题】:Swift 2 Parsing JSON - Cannot subscript a value of type 'AnyObject'Swift 2 Parsing JSON - 无法下标“AnyObject”类型的值
【发布时间】:2015-10-25 00:17:34
【问题描述】:

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

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"
    }
]}

【问题讨论】:

  • 你能打印 jsonResult 给我们看看它的样子吗?

标签: json swift2


【解决方案1】:

试试这个

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)")
    }
}

【讨论】:

  • 谢谢,但是 if 语句不起作用。循环永远不会执行。
  • @Daniel,尝试使用[[String: AnyObject]](我修复了答案)
【解决方案2】:

你可以这样做

let title : String
if let titleVal = item["Title"] as? String
{
   title = titleVal
   print(title)
}

这将负责检查Title 属性值是否为空。如果不为null,则读取该值并设置为titleVal变量。

如果你确定它永远不会有空值,你可以使用这段代码

let title = item["Title"] as! String

【讨论】:

  • 谢谢,我都试过了,它仍然无法编译,并给出与我的问题相同的错误。
猜你喜欢
  • 1970-01-01
  • 2023-03-30
  • 2015-08-08
  • 2016-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 2018-10-12
相关资源
最近更新 更多