问题
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