2016-04-25 48 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]