无法使用类型为“String”的索引下标[Dictionary <string,any =“”>]类型的值

时间:2017-03-20 19:40:17

标签: json swift dictionary swift3 alamofire

我正在尝试读取从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"])
          }
      }

  }
}

我得到的错误:

  

无法使用“String”类型的索引下载[Dictionary]类型的值

这是我正在使用的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的新手,非常感谢你!

1 个答案:

答案 0 :(得分:6)

错误的原因是该行:

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] {

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