解析JSON时,类型“Any”没有下标成员

时间:2017-05-11 07:47:44

标签: json swift subscript

func parseResponseData(response: AnyObject) {
    if let feedData = response["feed"] as? [String: Any]{
        let entryArray = feedData["entry"] as Any
        if let entry = entryArray as? [Any]{
            for object in entry{
                print(object)
                let appName = object["category"] as [String: Any]  // Error: Type "Any" has no subscript members.
            }   
        } 
    }
}

由于此错误,我无法解析响应,任何线索如何解决此问题。

JSON response

2 个答案:

答案 0 :(得分:0)

试试这个,entryArrayString : Any

的数组
func parseResponseData(response: AnyObject) {
    if let feedData = response["feed"] as? [String: Any]{
        let entryArray = feedData["entry"] as Any
        if let entry = entryArray as? [[String: Any]] {
            for object in entry {
                print(object)
                let appName = object["category"] as? [String: Any]
            }
        }
    }
}

答案 1 :(得分:0)

您必须告诉编译器所有下标集合类型的实际类型,Any是不够的。

使用JSON字典的类型别名

是有帮助的
typealias JSONDictionary = [String:Any]

func parseResponseData(response: Any) {
    if let feedData = response["feed"] as? JSONDictionary,
     let entryArray = feedData["entry"] as? [JSONDictionary] {
        for object in entryArray {
            print(object)
            if let category = object["category"] as? JSONDictionary {
                print(category)
            }
        } 
    }
}