【问题标题】:Could not cast value of type '__NSDictionaryM' to 'NSArray" [duplicate]无法将“__NSDictionaryM”类型的值转换为“NSArray”[重复]
【发布时间】:2016-04-25 06:25:41
【问题描述】:

这是我的代码的一部分:

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",

等。

这是我的错误:

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

在这一行:

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

我不明白为什么。我对 JSON 和 iOS 很陌生,但“响应”对我来说就像一本字典,我不知道为什么它是一个 NSArray,我不知道如何解决这个问题。任何帮助将不胜感激。

这不是重复的,因为其他帖子没有帮助我解决这个问题。

【问题讨论】:

    标签: ios json swift nsdictionary tumblr


    【解决方案1】:

    错误信息说

    无法将 actual 类型的 NSDictionary 转换为 expected 类型的 NSArray

    [NSDictionary] 表示字典数组,但response 的值显然是字典,用一对大括号表示。

    原来如此

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

    但建议使用 Swift 原生集合类型

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

    【讨论】:

      【解决方案2】:
      quoteDictionary = quotesData["response"] as! [NSArray]
      

      现在从NSArray of dictionaries 取这个值作为[quoteDictionary][0] //返回第一个

      现在以[quoteDictionary][0][blog] 访问该字典

      【讨论】:

        猜你喜欢
        • 2015-12-02
        • 2017-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-07
        • 1970-01-01
        • 2015-08-29
        相关资源
        最近更新 更多