不能将 [字典<字符串,任意>] 类型的值下标,索引类型为 'String'



我正在尝试读取从Alamofire返回给我的一些数据,但是在尝试导航JSON时出现此错误。这是我的代码:

Alamofire.request(requestURL).responseJSON { response in
if let JSON = response.result.value as? [Dictionary<String, Any>] {
if let reviews = JSON["reviews"] as? [Dictionary<String, Any>] { //Its giving me the error here
for review in reviews {
print(review["description"])
}
}
}
}

我得到的错误是:

无法将索引类型为"字符串"的 [字典] 类型的值下标

这是我正在使用的 JSON:

{
"item": {
"id": 1,
"name": "The Lord of the Rings: The Fellowship of the Ring",
"description": "A meek Hobbit from the Shire and eight companions set out on a journey to destroy the powerful One Ring and save Middle Earth from the Dark Lord Sauron."
},
"cast": {
"roles": [
{
"actor": {
"name": "Sean Astin"
},
"character": {
"name": "Sam"
}
}
]
},
"fullDescription": "An ancient Ring thought lost for centuries has been found, and through a strange twist in fate has been given to a small Hobbit named Frodo. When Gandalf discovers the Ring is in fact the One Ring of the Dark Lord Sauron, Frodo must make an epic quest to the Cracks of Doom in order to destroy it! However he does not go alone. He is joined by Gandalf, Legolas the elf, Gimli the Dwarf, Aragorn, Boromir and his three Hobbit friends Merry, Pippin and Samwise. Through mountains, snow, darkness, forests, rivers and plains, facing evil and danger at every corner the Fellowship of the Ring must go. Their quest to destroy the One Ring is the only hope for the end of the Dark Lords reign!",
"reviews": [
{
"description": "something",
"star": {
"value": 5
},
"userName": "some name"
}
]
}

任何想法??我是 Swift 的新手,非常感谢!

错误的原因是以下行:

if let JSON = response.result.value as? [Dictionary<String, Any>] {

告诉编译器JSON是一个数组。但随后在行中:

if let reviews = JSON["reviews"] as? [Dictionary<String, Any>] {

您尝试使用String索引访问该数组的元素。因此,编译器的错误。

但是您的顶级 JSON 是一个字典,而不是一个数组。所以改变这一行:

if let JSON = response.result.value as? [Dictionary<String, Any>] {

自:

if let JSON = response.result.value as? Dictionary<String, Any> {

或:

if let JSON = response.result.value as? [String : Any] {

这将修复您的错误并实际匹配您的数据。

最新更新