我正在尝试使用从S3下载的JSON文件的内容填充表(使用AWS SDK)。我在循环notifications
数组时遇到了困难,因为它似乎不是一个可迭代的对象。将整个对象强制转换为字典时返回Nil。我收到一条错误,指出我不能将notifications
字符串作为数组进行类型转换。我怎样才能将notifications
对象转换成我可以迭代的东西?
//JSON file
{
"notifications": [
{
"startDate": "2016-10-01 00:00:00",
"endDate": "2016-10-31 23:59:59",
"message": "October"
},
{
"startDate": "2016-11-01 00:00:00",
"endDate": "2016-11-31 23:59:59",
"message": "November"
}
]
}
//I omitted extraneous code
let task = s3.getObject(getObjectRequest)
if let output = task.result as? AWSS3GetObjectOutput{
do{
let json = try NSJSONSerialization.JSONObjectWithData((output.body! as? NSData)!, options: .AllowFragments)
//Debug code that works
print(json["notifications"]![0]) //Prints the first notification
print(json["notifications"]![0]["startDate"])
//Debug code that does not work
let opt = json["notifications"] as! NSArray //Can't typecast String as Array
//A 'for' loop does not work as well.
}catch{
print("Error serializing JSON [\(error)]")
}
}
答案 0 :(得分:0)
让opt = json ["通知"]为?数组//不能将字符串转换为数组
请试试这个
答案 1 :(得分:0)
json["notifications"] as! NSArray
工作但是你必须首先将NSJSONSerialization的结果转换为正确的类型,在你的情况下是字典:
do {
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] {
print(json["notifications"] as! NSArray)
}
} catch let error as NSError {
print(error.debugDescription)
}
或者,如果您愿意:
do {
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
print(json["notifications"] as! NSArray)
}
} catch let error as NSError {
print(error.debugDescription)
}