我尝试过以下示例来解析JSON文件(例如,此处发布的另一个问题的答案:https://stackoverflow.com/a/27206145/4040201)但无法使其工作。我现在在“let ... = item [”...“]上得到错误”不能下载'AnyObject'类型的值'作为?String“行。
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"
}
]}
答案 0 :(得分:2)
试试这个
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)")
}
}
答案 1 :(得分:0)
你可以这样做
let title : String
if let titleVal = item["Title"] as? String
{
title = titleVal
print(title)
}
这将检查Title
属性值是否为null。如果它不为null,它将读取该值并设置为titleVal
变量。
如果您确定它永远不会有空值,则可以使用此代码
let title = item["Title"] as! String