NSJSONSerialization上的Swift Dynamic Cast失败

时间:2014-12-15 07:11:23

标签: ios json swift nsdictionary nsjsonserialization

我有JSON Data看起来像:

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

我正在使用:

将其转换为NSDictionary
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(
 data,
 options: NSJSONReadingOptions.MutableContainers,
 error: nil)
as NSDictionary

3 个答案:

答案 0 :(得分:2)

您的JSON包含NSArray类型的根对象,而不是NSDictionary

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

答案 1 :(得分:1)

请参阅此..可能会对您有所帮助

this is my json

我已解析过这个..

它看起来像是相同的结果..

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是可变数组

答案 2 :(得分:1)

我经常使用这个。适用于JSON的数字和关联类型。它也适合你。我试过了。

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