不能从'Any'向下转换为更可选的类型'[String:AnyObject]?'

时间:2017-11-06 05:19:04

标签: ios json swift api serialization

我正在尝试从url中获取json。虽然序列化json它给出错误?

 static func fetchFeatureApp(){
            let urlString="http://ebmacs.net/ubereats/Api/all_product?id=1"
            let url = URL(string: urlString)!

         URLSession.shared.dataTask(with: URLRequest(url: url)){ (data, responce, error) in
            if error != nil
                {
                    print(error)
                    return
                }
                do{
                   let json=try (JSONSerialization.jsonObject(with: data!, options: .mutableContainers)) //as! [String:AnyObject]?//as! [AnyObject]?//as! String? //as! [String:AnyObject]//as! [String: Any]
 //////////Error here

                    //let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String: Any] //program is crashing 
                    var appCategories=[AppCategory]()
                    for dict in json["products"] as! [[String :AnyObject]]{///////Error Here
                        let appCategory = AppCategory()
                        appCategory.setValuesForKeys(dict)
                        appCategories.append(appCategory)
                    }
                    print(appCategories)
                }catch let err{
                    print(error)
                }
            }.resume()

        }

Json的课程是

class App:NSObject  {
    var product_id:NSNumber?
    var product_name:String?
    var product_description:String?
    var image_url:String?
    var product_price:NSNumber?
    var name:String?
}

image description here

在以下几行我收到错误:

错误1:

 `let json=try (JSONSerialization.jsonObject(with: data!, options: .mutableContainers)) //as! [String:AnyObject]?//as! [AnyObject]?//as! String? //as! [String:AnyObject]//as! [String: Any]`
  

不能从'Any'向下转换为更可选的类型'[String:   AnyObject]?“

错误2:

for dict in json["products"] as! [[String :AnyObject]]{ /////////////error
  

类型'Any'没有下标成员

如何删除这些错误?

2 个答案:

答案 0 :(得分:1)

解析JSON的推荐方法是使用可选绑定安全地解包可选项。

请阅读JSON。这很容易。 {}代表字典(Swift中的[String:Any]),[]数组([[String:Any]])和.mutableContainers无论如何都是Swift中的无意义。

根对象是字典,键products的值是数组

struct AppCategory {
    let id, name, description, url, price : String
}

do {
    if let jsonResult = try JSONSerialization.jsonObject(with:data!) as? [String:Any] {
        if let products = jsonResult["products"] as? [[String:String]] {
            var appCategories = [AppCategory]()
            for product in products {
                let category = AppCategory(id: product["product_id"] ?? "",
                                           name: product["product_name"] ?? "",
                                           description: product["product_description"] ?? "",
                                           url: product["image_url"] ?? "",
                                           price: product["product_price"] ?? "")
                appCategories.append(category)
            }
            print(appCategories)
        }
    }
} catch {
    print(error)
}

答案 1 :(得分:-2)

试试这个:

let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:Any]

编辑:这只有在json中的顶级对象实际上是字典而不是数组时才有效。如果您可以发布json响应的编辑版本,将会很有帮助。

此代码适用于我的网址。