Swift Dynamic Cast Failed on NSJSONSerialization

我与影子孤独终老i 提交于 2019-12-06 14:01:16

问题


I have a JSON Data which looks like:

[ 
{ "Name" : "Ernst Handel", "City" : "Graz", "Country" : "Austria" },
{ "Name" : "Wolski Zajazd", "City" : "Warszawa", "Country" : "Poland" }
]

and I am converting it to NSDictionary using:

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

回答1:


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]()
}



回答2:


Your JSON contains root object of type NSArray, not NSDictionary

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



回答3:


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



来源:https://stackoverflow.com/questions/27478985/swift-dynamic-cast-failed-on-nsjsonserialization

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