我尝试从一个数组中获取一个String,我将重复一个数组。
let parsed = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments)
for item in parsed as! [Dictionary<String, AnyObject>]{
doSomething(item["title"])
}
xCode正在打印以下错误,同时获得&#34; title&#34;来自&#34; item&#34;:
Cannot subscript a value of Type 'Dictionary<String, AnyObject>' with an index of type 'String'
我的错误是什么?
答案 0 :(得分:0)
尝试这样的事情
if let parsed = try? NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments) as! [String: AnyObject] {
for (key, value) in parsed {
print(key)
print(value)
// do something
}
}
我刚试过这个简单的代码 - 这适用于swift 2.0
let jsonData = "{\"hello\":\"world\"}".dataUsingEncoding(NSUTF8StringEncoding)
if let parsed = try? NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.AllowFragments) as! [String: AnyObject] {
for (key, value) in parsed {
print(key)
print(value)
// do something
}
}
答案 1 :(得分:0)
也许这可能会对你有所帮助。尝试一下,让我知道它是否有效。
if let parsed = (try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions(rawValue: 0)) as? [[String : AnyObject]]) {
for items in parsed {
if let item = items as? [String : AnyObject] {
let title = item["title"]
print("@@@ item :: \(title)")
}
}}