2016-04-25 90 views
1

型 '__NSDictionaryM' 的值。這是我的我的代碼部分:無法轉換爲「的NSArray」

let quotesData = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary 


var quoteDictionary: [NSDictionary]! 
quoteDictionary = quotesData["response"] as! [NSDictionary] 

這是從Tumblr API的JSON的一部分:

{ 
    "meta": { 
    "status": 200, 
    "msg": "OK" 
}, 
    "response": { 
    "blog": { 
    "title": "A Sea of Quotes", 
    "name": "aseaofquotes", 
    "total_posts": 10089, 
    "posts": 10089, 
    "url": "http://www.aseaofquotes.com/", 
    "updated": 1461556819, 
    "description": "", 
    "is_nsfw": false, 
    "ask": true, 
    "ask_page_title": "Thanks in advance if you leave a nice message and/or correct quote sources. Please check FAQs before sending. I do not respond to Anonymous questions, but I may answer your anon question in the FAQ. :) Warning: It may take me a while to reply.", 
    "ask_anon": true, 
    "submission_page_title": "Submit A Quote", 
    "share_likes": false 
}, 
"posts": [ 
    { 
    "blog_name": "aseaofquotes", 
    "id": 143359277336, 
    "post_url": "http://www.aseaofquotes.com/post/143359277336/marlon-james-a-brief-history-of-seven-killings", 
    "slug": "marlon-james-a-brief-history-of-seven-killings", 
    "type": "photo", 
    "date": "2016-04-25 04:00:18 GMT", 
    "timestamp": 1461556818, 
    "state": "published", 
    "format": "html", 
    "reblog_key": "YiiqHC46", 

ETC 。

這是我的錯誤:

Could not cast value of type '__NSDictionaryM' (0x101925d38) to 'NSArray' (0x101925900). 

在這條線上:

quoteDictionary = quotesData["response"] as! [NSDictionary] 

我不明白爲什麼。我對JSON和iOS很新,但「響應」看起來像是一本字典,我不知道爲什麼它是NSArray,我不知道如何解決這個問題。任何幫助將不勝感激。

這不是重複的,因爲其他帖子並沒有幫助我解決這個問題。

回答

2

該錯誤消息表示

Could not cast the actual type NSDictionary to the expected type NSArray

[NSDictionary]裝置的陣列字典,但response的值顯然是字典,表示感覺到一對大括號。

所以它實際上

let quoteDictionary = quotesData["response"] as! NSDictionary 

但建議使用斯威夫特本地集合類型

let quoteDictionary = quotesData["response"] as! Dictionary<String,AnyObject> 
0
quoteDictionary = quotesData["response"] as! [NSArray] 

立即採取從NSArray of dictionaries這個值作爲[quoteDictionary][0] //返回第一個

立即訪問該字典作爲[quoteDictionary][0][blog]