Swift3 JSON错误 - 无法下标AnyObject类型的值

时间:2017-03-01 13:43:25

标签: json swift swift3 swift2 swift2.3

从swift2到swift3的转换中获取错误(无法将'AnyObject'类型的下标值)。代码来自于使用swift2.3编写的github的垄断游戏

    let bundle = Bundle.main
    let path = bundle.path(forResource: "properties", ofType: "json")
    var error: NSError?
    var data: NSData = NSData(contentsOfFile: path!)!
    do {
        let json = try? JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.allowFragments) as AnyObject

        if let objects = json as? [AnyObject] {
            for obj in objects {
                var category = Category.special
                switch obj["Group"] as String! {    //error!
                    case "Brown": category = .brown
                    case "LightBlue": category = .lightBlue
                    case "Pink": category = .pink
                    case "Orange": category = .orange
                    case "Red": category = .red
                    case "Yellow": category = .yellow
                    case "Green": category = .green
                    case "Blue": category = .blue
                    default: category = .special
                }

                let name = obj["Name"] as String     //error!
                let price = obj["Price"] as Int      //error!
                let tile = obj["Position"] as Int    //error!
                var rent = 0
                if let r = obj["Rent"] as? Int {    //error! Ambiguous use of "subscript"
                    rent = r
                }

                let property = Property(name: name, category: category, price: price, tile: tile, rent: rent)
                game.tiles.append(property)
            }
    }
} catch {
print("error")
}

JSON: [   {   “名称”: “GO”,   “位置”:1,   “价格”:0,   “租”:0,   “本集团”: “GO”   }, 等]

1 个答案:

答案 0 :(得分:1)

将您的json指定为[[String:Any]]之类的字典数组,而不是将其声明为[AnyObject]

if let objects = (try? JSONSerialization.jsonObject(with: data as Data, options: [])) as? [[String:Any]] {
     for obj in objects {
         var category = Category.special
         switch obj["Group"] as! String {
              case "Brown": category = .brown
              case "LightBlue": category = .lightBlue
              case "Pink": category = .pink
              case "Orange": category = .orange
              case "Red": category = .red
              case "Yellow": category = .yellow
              case "Green": category = .green
              case "Blue": category = .blue
              default: category = .special
         }
         //Add your other code
     }
}