Swift Dynamic Cast Failed on NSJSONSerialization

北城以北 提交于 2019-12-04 18:17:29

I usually use this. Works for both numeric and associative types of JSON. It works for your as well. I tried.

func JSONParseArray(jsonString: String) -> [AnyObject] {
if let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding) {
if let array = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: nil)  as? [AnyObject] {
    return array
}
}
return [AnyObject]()
}

Your JSON contains root object of type NSArray, not NSDictionary

var jsonResult: NSArray = NSJSONSerialization.JSONObjectWithData(
 data,
 options: NSJSONReadingOptions.MutableContainers,
 error: nil)
as NSArray

Refer this..it may help you

this is my json

and i have parsed like this..

Its look like same result..

var err: NSError
        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println(jsonResult)
      self.productsArray = jsonResult.valueForKey("products") as NSMutableArray
          println( self.productsArray.count);
        var toInt: Int = self.productsArray.count
        for value in 1...toInt-1
        {
            self.valuesArray.addObject(productsArray.objectAtIndex(value).valueForKey("item_name")!)

        }

self.valuesArray,self.productsArray are mutable array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!