无法将 _NCSFDictionary 类型的值转换为 NSArray Swift 2

Posted

技术标签:

【中文标题】无法将 _NCSFDictionary 类型的值转换为 NSArray Swift 2【英文标题】:Could not cast value of type _NCSFDictionary to NSArray Swift 2 【发布时间】:2015-11-24 09:40:42 【问题描述】:

在我的代码中,我正在执行一个保护语句,这样我就可以遍历 JSON 并获取我想要的数据,但我不断收到一条错误消息,提示“无法将 '__NSCFDictionary' 类型的值转换为 'NSArray'。”这是我的代码:

urlSession.dataTaskWithURL(urlWithJSON, completionHandler: (data, response, error) -> Void in
     do 
        let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! NSDictionary
        guard let query:[AnyObject] = json["query"] as! [AnyObject] else 
             throw StockError.InvalidArray
         

我强制向下转换为 NSDictionary,因为我需要获取 JSON 数据中特定项目的键,当尝试强制向下转换为 NSArray 时,我收到一个错误,提示它需要一个 int。

编辑:这是用于获取 JSON 数据的 javascript 代码: var sync = require("同步请求");

var urlBeginning = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22";
var urlEnding = "%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";

var getStockValue = function(symbol) 
    var url = urlBeginning + symbol + urlEnding;
    var res = sync('GET', url);
    var data = JSON.parse(res.getBody().toString('utf8'));
    console.log(data);
    console.log(data.query.results);
;

getStockValue("GOOG");

哪些输出:

 query: 
    count: 1,
     created: '2015-11-24T10:13:49Z',
     lang: 'en-US',
     diagnostics: 
       url: [Object],
        publiclyCallable: 'true',
        cache: [Object],
        query: [Object],
        javascript: [Object],
        'user-time': '30',
        'service-time': '10',
        'build-version': '0.2.311' ,
     results:  quote: [Object]   
 quote: 
    symbol: 'GOOG',
     Ask: '754.13',
     AverageDailyVolume: '2244760',
     Bid: '749.49',
     AskRealtime: null,
     BidRealtime: null,
     BookValue: '169.03',
     Change_PercentChange: '-0.62 - -0.08%',
     Change: '-0.62',
     Commission: null,
     Currency: 'USD',
     ChangeRealtime: null,
     AfterHoursChangeRealtime: null,
     DividendShare: null,
     LastTradeDate: '11/23/2015',
     TradeDate: null,
     EarningsShare: '23.72',
     ErrorIndicationreturnedforsymbolchangedinvalid: null,
     EPSEstimateCurrentYear: '28.99',
     EPSEstimateNextYear: '34.22',
     EPSEstimateNextQuarter: '7.80',
     DaysLow: '751.82',
     DaysHigh: '762.71',
     YearLow: '486.23',
     YearHigh: '762.71',
     HoldingsGainPercent: null,
     AnnualizedGain: null,
     HoldingsGain: null,
     HoldingsGainPercentRealtime: null,
     HoldingsGainRealtime: null,
     MoreInfo: null,
     OrderBookRealtime: null,
     MarketCapitalization: '519.91B',
     MarketCapRealtime: null,
     EBITDA: '23.30B',
     ChangeFromYearLow: '269.75',
     PercentChangeFromYearLow: '+55.48%',
     LastTradeRealtimeWithTime: null,
     ChangePercentRealtime: null,
     ChangeFromYearHigh: '-6.73',
     PercebtChangeFromYearHigh: '-0.88%',
     LastTradeWithTime: '4:00pm - <b>755.98</b>',
     LastTradePriceOnly: '755.98',
     HighLimit: null,
     LowLimit: null,
     DaysRange: '751.82 - 762.71',
     DaysRangeRealtime: null,
     FiftydayMovingAverage: '696.65',
     TwoHundreddayMovingAverage: '614.49',
     ChangeFromTwoHundreddayMovingAverage: '141.49',
     PercentChangeFromTwoHundreddayMovingAverage: '+23.03%',
     ChangeFromFiftydayMovingAverage: '59.33',
     PercentChangeFromFiftydayMovingAverage: '+8.52%',
     Name: 'Alphabet Inc.',
     Notes: null,
     Open: '757.45',
     PreviousClose: '756.60',
     PricePaid: null,
     ChangeinPercent: '-0.08%',
     PriceSales: '7.25',
     PriceBook: '4.48',
     ExDividendDate: null,
     PERatio: '31.87',
     DividendPayDate: null,
     PERatioRealtime: null,
     PEGRatio: '1.48',
     PriceEPSEstimateCurrentYear: '26.08',
     PriceEPSEstimateNextYear: '22.09',
     Symbol: 'GOOG',
     SharesOwned: null,
     ShortRatio: '1.81',
     LastTradeTime: '4:00pm',
     TickerTrend: null,
     OneyrTargetPrice: '853.67',
     Volume: '1415536',
     HoldingsValue: null,
     HoldingsValueRealtime: null,
     YearRange: '486.23 - 762.71',
     DaysValueChange: null,
     DaysValueChangeRealtime: null,
     StockExchange: 'NMS',
     DividendYield: null,
     PercentChange: '-0.08%'  

【问题讨论】:

你能提供json数据吗?看起来您要转换为数组的东西是 JSON 对象而不是数组。 @JanGreve 当然,query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22goog%22)&format=json&diagnostics=true&env=store%3A%2F% 2Fdatatables.org%2Falltableswithkeys&callback= 这是 Alphabet 份额值的 url,在我的代码中,我使用 (ticker) 可以找到 goog 的位置,以便在获取数据时获得用户输入。 这对我来说不能卷曲。您能否将您实际解析的数据记录为 UTF8 字符串并相应地编辑您的问题? 我已经在编辑中添加了 【参考方案1】:

好的。因此,您正在从该 JSON 访问 query,这是一个 JSON 对象。这些被映射到 NSDictionaries,所以转换为 [AnyObject] 肯定会失败。

投到NSDictionary,你会没事的。

【讨论】:

以上是关于无法将 _NCSFDictionary 类型的值转换为 NSArray Swift 2的主要内容,如果未能解决你的问题,请参考以下文章

js中由var获取的值转转换为long值

玩转web之json---将表单通过serialize()方法获取的值转成json

[C++]jsoncpp中将整个Json::Value转成std::string或者把里面值转成string类型

[C++]json cpp中将整个Json::Value转成std::string或者把里面值转成string类型

无法将类型 '(Any) -> ()' 的值转换为预期的参数类型 '(_) -> _'

无法将“__NSCFNumber”()类型的值快速转换为“NSArray”