尝试解析JSON时无法下标值错误

时间:2016-07-27 14:29:16

标签: json swift dictionary

我是SWIFT的新手,从Android开发开始,尝试将json解析为Dictionary但得到'不能下标类型的值' [AnyObject]'索引类型'字符串'在

        if let dict = Utils.convertStringToDictionary(response)! as? [String: AnyObject]{

            if let response = dict["response"] as? [AnyObject]{

                if let first_name = response["first_name"] as? String {//error
                NSLog("first_name = \(first_name)")
                }
            }

        }

以防万一,这是Utils.convertStringToDictionary方法:

public static func convertStringToDictionary(text: String) -> [String:AnyObject]? {
    if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [String:AnyObject]
            return json
        } catch {
            NSLog("Something went wrong")
        }
    }
    return nil
}

1 个答案:

答案 0 :(得分:-1)

这一行:

if let response = dict["response"] as? [AnyObject]

您正在将dict["response"]作为包含AnyObject类型的项目的数组进行投射。

然后用这一行:

if let first_name = response["first_name"] as? String

您正试图访问此数组,就像它是字典一样。

这就是编译器告诉你的原因

  

不能使用String

类型的索引下标[AnyObject]类型的值

因为[AnyObject]是一个数组而且你不能用带字典的字符串下标一个数组,它只接受带索引的下标。