我创建了一个下载json文件的数据任务。 json是一系列字典。这是数据样本:
[
{
"userName": "Elon Musk",
"comment": "This is a fantastic Beer. I highly recommend it!"
},
{
"userName": "SuperUser Account",
"comment": "I agree with Elon.. It rocks!"
}
]
问题是我无法将json强制转换为[String: Any]
。我只能把它投到[Any]
。以下是相关代码:
guard let json = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: Any] else {
print("error trying to convert data to JSON")
return
}
// now we have the json, let's just print it to prove we can access it
print("The json is: " + json.description)
施放为[Any]
json打印正常。演员失败了吗?
请问?
答案 0 :(得分:1)
你的json是array
而不是字典..只是把它投到[[String:Any]]
guard let json = try JSONSerialization.jsonObject(with: responseData, options: []) as? [[String: Any]] else {
print("error trying to convert data to JSON")
return
}
for dict in json {
print(dict["userName"])
}