0

is there a way to decode the following structure in Swift 5, when some Keywords (in this case for example "Time Series (5min)") change in different requests to the api?

If there is a way, which one is the easiest and does SwiftyJSON-Library maybe help to simplify that process?

{
  "Meta Data": {
    "1. Information": "Intraday (5min) open, high, low, close prices and volume",
    "2. Symbol": "MSFT",
    "3. Last Refreshed": "2020-03-23 16:00:00",
    "4. Interval": "5min",
    "5. Output Size": "Compact",
    "6. Time Zone": "US/Eastern"
  },
  "Time Series (5min)": {
    "2020-03-23 16:00:00": {
      "1. open": "136.1900",
      "2. high": "137.3400",
      "3. low": "135.5600",
      "4. close": "135.5700",
      "5. volume": "3065003"
    },
    "2020-03-23 15:55:00": {
      "1. open": "134.0700",
      "2. high": "136.4200",
      "3. low": "133.7000",
      "4. close": "136.1800",
      "5. volume": "1924093"
    }
  }
}

I got this already, so the Timestamps are not the problem. The Problem is: How can I generalize this when "Time Series (5min)" changes from request to request?

struct Stockdata: Codable {
    let metaData: MetaData
    let timeSeries1Min: [String: TimeSeries]

    enum CodingKeys: String, CodingKey {
        case metaData = "Meta Data"
        case timeSeries1Min = "Time Series (1min)"
    }
    struct MetaData: Codable {
        let information, symbol, lastRefreshed, interval, outputSize, timeZone: String?
        enum CodingKeys: String, CodingKey {
            case information = "1. Information"
            case symbol = "2. Symbol"
            case lastRefreshed = "3. Last Refreshed"
            case interval = "4. Interval"
            case outputSize = "5. Output Size"
            case timeZone = "6. Time Zone"
        }
    }
    struct TimeSeries: Codable {
        let open, high, low, close, volume: String?
        enum CodingKeys: String, CodingKey {
            case open = "1. open"
            case high = "2. high"
            case low = "3. low"
            case close = "4. close"
            case volume = "5. volume"
        }
    }
}
  • this might help a little: https://stackoverflow.com/questions/50713638/swift-codable-with-dynamic-keys – HalR Mar 24 '20 at 00:25
  • If I try it with multiple ones it works, but the Compiler doesn't take String in front of my [String: TimeSeries]. So it's not supposed to be in an array like this: [String:[Inner]], instead I thought of something like this: String:[Inner] – lennardkorte Mar 24 '20 at 00:48
  • I really don't understand why this question got closed... It's not been answered in the linked article, please help! I asked specifically about what happens if the "Time Series (5min)" changes dynamically. – lennardkorte Mar 24 '20 at 13:20

0 Answers0