如何在swift中解码JSON

时间:2017-08-23 22:12:31

标签: json swift stock

{
  "Meta Data": {
    "1. Information": "Daily Prices (open, high, low, close) and Volumes",
    "2. Symbol": "FB",
    "3. Last Refreshed": "2017-08-23 16:00:00",
    "4. Output Size": "Compact",
    "5. Time Zone": "US/Eastern"
  },
  "Time Series (Daily)": {
    "2017-08-23 16:00:00": {
      "1. open": "168.8400",
      "2. high": "169.3600",
      "3. low": "168.2000",
      "4. close": "168.7100",
      "5. volume": "8198515"
    },
    "2017-08-22": {
      "1. open": "168.2800",
      "2. high": "169.8700",
      "3. low": "167.1500",
      "4. close": "169.6400",
      "5. volume": "11333260"
    },
    "2017-08-21": {
      "1. open": "167.1600",
      "2. high": "168.0000",
      "3. low": "165.8200",
      "4. close": "167.7800",
      "5. volume": "11880823"
    },
    "2017-08-18": {
      "1. open": "166.8400",
      "2. high": "168.6700",
      "3. low": "166.2100",
      "4. close": "167.4100",
      "5. volume": "14933261"
    },
    "2017-08-17": {
      "1. open": "169.3400",
      "2. high": "169.8600",
      "3. low": "166.8500",
      "4. close": "166.9100",
      "5. volume": "16791591"
    },
    "2017-08-16": {
      "1. open": "171.2500",
      "2. high": "171.3800",
      "3. low": "169.2400",
      "4. close": "170.0000",
      "5. volume": "15580549"
    }
  }
}

我的问题是,如果日期(例如:2017-08-02)不断变化,如何从JSON日期获取所有信息(例如:4.close)。

到目前为止,在我的项目中,我只能获得某个日期的数据。

func fetchStockDataCalendar() {

    let url = URL(string: "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=\(symbol)&apikey=\(apiKey)")

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil {
            print ("ERROR")
        } else {
            if let content = data {
                do {
                    //Array
                    let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject

                    if let Time = myJson["Time Series (Daily)"] as? NSDictionary  {

                        if let Day = Time["2017-06-21"] as? NSDictionary {

                            if let CloseStockData = Day["4. close"] as? String {
                                print("2017-06-21 CloseStock-> \(CloseStockData)$")
                            }
                        }
                    }
                }  catch  {
                    print(error.localizedDescription)
                }
            }
        }
    }
    task.resume()
}

what I get

2 个答案:

答案 0 :(得分:0)

使用for循环迭代字典键和值,如下所示:

<span title='the tooltip for LARC'>

根据您的评论我也添加了

if let time = myJson["Time Series (Daily)"] {
    for (key, value) in time {
        if let close = value["4. close"] {
            print("\(key) CloseStock-> \(close)")
        }
    }
}

答案 1 :(得分:0)

这是你的func与上面的代码,但作为NSDictionary。我的控制台显示了所有关闭。

2017-10-24 CloseStock-&gt; 256.5600

2018-02-22 CloseStock-&gt; 270.4000

func fetchStockDataCalendar() {

    let url = URL(string: "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=\("SPY")&apikey=\(alphaApiKey)")

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil {
            print ("ERROR")
        } else {
            if let content = data {
                do {
                    let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject

                    if let time = myJson["Time Series (Daily)"] as? NSDictionary  {
                        for (key, value) in time {
                            if let value = value as? Dictionary<String, String> {
                                if let close = value["4. close"] {
                                    print("\(key) CloseStock-> \(close)")
                                }
                            }
                        }
                    }

                }  catch  {
                    print(error.localizedDescription)
                }
            }
        }
    }
    task.resume()
}