如何在Swift中显示JSON中的特定数据?

时间:2015-01-17 04:43:08

标签: json parsing swift ios8

嘿伙计们我正在尝试开发一个简单的应用程序来从雅虎财经获取数据。现在我可以从雅虎获得JSON响应,但我只需要一个来自它的数据,即股票公司名称。那我怎么能实现呢?

我的代码:

import UIKit

class ViewController: UIViewController, NSURLConnectionDelegate {

lazy var data = NSMutableData()

override func viewDidLoad() {
    super.viewDidLoad()
    startConnection()
}

    func startConnection(){
    var baseUrl:NSURL = NSURL(string:"http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22PETR4.SA%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=")!
    var request: NSURLRequest = NSURLRequest(URL: baseUrl)
    var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!

}

func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {

    // Recieved a new request, clear out the data object
    self.data = NSMutableData()

}

func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
    // Append the recieved chunk of data to our data object
    self.data.appendData(data)
}



func connectionDidFinishLoading(connection: NSURLConnection!) {
    // Request complete, self.data should now hold the resulting info
    // Convert the retrieved data in to an object through JSON deserialization

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

    println(jsonResult)
}
}

响应:

{
query =     {
    count = 1;
    created = "2015-01-17T04:34:11Z";
    diagnostics =         {
        "build-version" = "0.2.212";
        cache =             {
            content = 5d1e1de680846a307c9874dc3d6878dc;
            "execution-start-time" = 4;
            "execution-stop-time" = 5;
            "execution-time" = 1;
            method = GET;
            type = MEMCACHED;
        };
        javascript =             {
            "execution-start-time" = 3;
            "execution-stop-time" = 104;
            "execution-time" = 101;
            "instructions-used" = 66631;
            "table-name" = "yahoo.finance.quotes";
        };
        publiclyCallable = true;
        query =             {
            content = "select * from csv where url=@url and columns='Ask,AverageDailyVolume,Bid,AskRealtime,BidRealtime,BookValue,Change&PercentChange,Change,Commission,Currency,ChangeRealtime,AfterHoursChangeRealtime,DividendShare,LastTradeDate,TradeDate,EarningsShare,ErrorIndicationreturnedforsymbolchangedinvalid,EPSEstimateCurrentYear,EPSEstimateNextYear,EPSEstimateNextQuarter,DaysLow,DaysHigh,YearLow,YearHigh,HoldingsGainPercent,AnnualizedGain,HoldingsGain,HoldingsGainPercentRealtime,HoldingsGainRealtime,MoreInfo,OrderBookRealtime,MarketCapitalization,MarketCapRealtime,EBITDA,ChangeFromYearLow,PercentChangeFromYearLow,LastTradeRealtimeWithTime,ChangePercentRealtime,ChangeFromYearHigh,PercebtChangeFromYearHigh,LastTradeWithTime,LastTradePriceOnly,HighLimit,LowLimit,DaysRange,DaysRangeRealtime,FiftydayMovingAverage,TwoHundreddayMovingAverage,ChangeFromTwoHundreddayMovingAverage,PercentChangeFromTwoHundreddayMovingAverage,ChangeFromFiftydayMovingAverage,PercentChangeFromFiftydayMovingAverage,Name,Notes,Open,PreviousClose,PricePaid,ChangeinPercent,PriceSales,PriceBook,ExDividendDate,PERatio,DividendPayDate,PERatioRealtime,PEGRatio,PriceEPSEstimateCurrentYear,PriceEPSEstimateNextYear,Symbol,SharesOwned,ShortRatio,LastTradeTime,TickerTrend,OneyrTargetPrice,Volume,HoldingsValue,HoldingsValueRealtime,YearRange,DaysValueChange,DaysValueChangeRealtime,StockExchange,DividendYield'";
            "execution-start-time" = 5;
            "execution-stop-time" = 95;
            "execution-time" = 90;
            params = "{url=[http://download.finance.yahoo.com/d/quotes.csv?f=aa2bb2b3b4cc1c3c4c6c8dd1d2ee1e7e8e9ghjkg1g3g4g5g6ii5j1j3j4j5j6k1k2k4k5ll1l2l3mm2m3m4m5m6m7m8nn4opp1p2p5p6qrr1r2r5r6r7ss1s7t1t7t8vv1v7ww1w4xy&s=PETR4.SA]}";
        };
        "service-time" = 91;
        url =             (
                            {
                content = "http://www.datatables.org/yahoo/finance/yahoo.finance.quotes.xml";
                "execution-start-time" = 1;
                "execution-stop-time" = 1;
                "execution-time" = 0;
            },
                            {
                content = "http://download.finance.yahoo.com/d/quotes.csv?f=aa2bb2b3b4cc1c3c4c6c8dd1d2ee1e7e8e9ghjkg1g3g4g5g6ii5j1j3j4j5j6k1k2k4k5ll1l2l3mm2m3m4m5m6m7m8nn4opp1p2p5p6qrr1r2r5r6r7ss1s7t1t7t8vv1v7ww1w4xy&s=PETR4.SA";
                "execution-start-time" = 5;
                "execution-stop-time" = 95;
                "execution-time" = 90;
            }
        );
        "user-time" = 106;
    };
    lang = "en-us";
    results =         {
        quote =             {
            AfterHoursChangeRealtime = "N/A - N/A";
            AnnualizedGain = "<null>";
            Ask = "9.45";
            AskRealtime = "9.45";
            AverageDailyVolume = 80999600;
            Bid = "9.44";
            BidRealtime = "9.44";
            BookValue = "27.652";
            Change = "+0.10";
            ChangeFromFiftydayMovingAverage = "-0.9209";
            ChangeFromTwoHundreddayMovingAverage = "-7.3725";
            ChangeFromYearHigh = "-15.46";
            ChangeFromYearLow = "+1.40";
            ChangePercentRealtime = "N/A - +1.07%";
            ChangeRealtime = "+0.10";
            "Change_PercentChange" = "+0.10 - +1.07%";
            ChangeinPercent = "+1.07%";
            Commission = "<null>";
            Currency = BRL;
            DaysHigh = "9.63";
            DaysLow = "9.24";
            DaysRange = "9.24 - 9.63";
            DaysRangeRealtime = "N/A - N/A";
            DaysValueChange = "- - +1.07%";
            DaysValueChangeRealtime = "N/A - N/A";
            DividendPayDate = "<null>";
            DividendShare = "0.9672";
            DividendYield = "10.36";
            EBITDA = "66.171B";
            EPSEstimateCurrentYear = "0.00";
            EPSEstimateNextQuarter = "0.00";
            EPSEstimateNextYear = "0.00";
            EarningsShare = "1.535";
            ErrorIndicationreturnedforsymbolchangedinvalid = "<null>";
            ExDividendDate = "3-Apr-14";
            FiftydayMovingAverage = "10.3609";
            HighLimit = "<null>";
            HoldingsGain = "<null>";
            HoldingsGainPercent = "- - -";
            HoldingsGainPercentRealtime = "N/A - N/A";
            HoldingsGainRealtime = "<null>";
            HoldingsValue = "<null>";
            HoldingsValueRealtime = "<null>";
            LastTradeDate = "1/16/2015";
            LastTradePriceOnly = "9.44";
            LastTradeRealtimeWithTime = "N/A - <b>9.44</b>";
            LastTradeTime = "2:08pm";
            LastTradeWithTime = "Jan 16 - <b>9.44</b>";
            LowLimit = "<null>";
            MarketCapRealtime = "<null>";
            MarketCapitalization = "123.1B";
            MoreInfo = cnpI;
            Name = "PETROBRAS   -PN";
            Notes = "<null>";
            OneyrTargetPrice = "<null>";
            Open = "9.46";
            OrderBookRealtime = "<null>";
            PEGRatio = "<null>";
            PERatio = "6.08";
            PERatioRealtime = "<null>";
            PercebtChangeFromYearHigh = "-62.09%";
            PercentChange = "+1.07%";
            PercentChangeFromFiftydayMovingAverage = "-8.89%";
            PercentChangeFromTwoHundreddayMovingAverage = "-43.85%";
            PercentChangeFromYearLow = "+17.41%";
            PreviousClose = "9.34";
            PriceBook = "0.34";
            PriceEPSEstimateCurrentYear = "<null>";
            PriceEPSEstimateNextYear = "<null>";
            PricePaid = "<null>";
            PriceSales = "0.38";
            SharesOwned = "<null>";
            ShortRatio = "<null>";
            StockExchange = "Sao Paolo";
            Symbol = "PETR4.SA";
            TickerTrend = "&nbsp;======&nbsp;";
            TradeDate = "<null>";
            TwoHundreddayMovingAverage = "16.8125";
            Volume = 56271000;
            YearHigh = "24.90";
            YearLow = "8.04";
            YearRange = "8.04 - 24.90";
            symbol = "PETR4.SA";
        };
    };
};
}

1 个答案:

答案 0 :(得分:0)

从NSJSONSerialization返回的对象是标准的NSDictionary,您可以这样操作它。因此,要获得公司名称,您需要访问:

  • 获取&#34;查询&#34; NSJSONSerialization返回的对象的字典
  • 获得&#34;结果&#34;查询字典中的字典
  • 得到&#34;引用&#34;结果词典中的字典
  • 最后,从引用词典中获取名称对象。

您可以使用此代码:

var query: NSDictionary = jsonResult["query"] as NSDictionary 
var results: NSDictionary = query["results"] as NSDictionary 
var quote: NSDictionary = results["quote"] as NSDictionary
var companyName: String = quote["Name"] as String
println(companyName)