Search code examples
jsonswiftdatemodeldateformatter

Swift, JSON model


I have a question regarding building a JSON model namely, I should declare a date that will be different each day - in this case: "2020-11-19" as below.

This is a response for the current day.

{
  "dates": {
    "2020-11-19": {
      "countries": {
        "Poland": {
          "date": "2020-11-19",
          "id": "poland",
          "links": [
            {
              "href": "/api/2020-11-19/country/poland",
              "rel": "self",
              "type": "GET"
            }
          ],
          "name": "Poland",
          "name_es": "Polonia",
          "name_it": "Polonia",
          "regions": [],
          "source": "John Hopkins University",
          "today_confirmed": 796798,
          "today_deaths": 12088,
          "today_new_confirmed": 23975,
          "today_new_deaths": 637,
          "today_new_open_cases": 4335,
          "today_new_recovered": 19003,
          "today_open_cases": 422824,
          "today_recovered": 361886,
          "today_vs_yesterday_confirmed": 0.03102262743215456,
          "today_vs_yesterday_deaths": 0.05562832940354556,
          "today_vs_yesterday_open_cases": 0.010358695210626712,
          "today_vs_yesterday_recovered": 0.055421236981710864,
          "yesterday_confirmed": 772823,
          "yesterday_deaths": 11451,
          "yesterday_open_cases": 418489,
          "yesterday_recovered": 342883
        }
      },
      "info": {
        "date": "2020-11-19 00:00CET",
        "date_generation": "2020-11-19 22:34",
        "yesterday": "2020-11-18 00:00CET"
      }
    }
  },
  "metadata": {
    "by": "Narrativa & AppliedXL",
    "url": [
      "wwww.narrativa.com",
      "www.appliedxl.com"
    ]
  },
  "total": {
    "date": "2020-11-19",
    "name": "Total",
    "name_es": "Total",
    "name_it": "Total",
    "rid": "#total",
    "source": "Narrativa",
    "today_confirmed": 56684618,
    "today_deaths": 1356365,
    "today_new_confirmed": 525111,
    "today_new_deaths": 8186,
    "today_new_open_cases": 273944,
    "today_new_recovered": 242981,
    "today_open_cases": 19082735,
    "today_recovered": 36245518,
    "today_vs_yesterday_confirmed": 0.009350349175964112,
    "today_vs_yesterday_deaths": 0.00607189401407382,
    "today_vs_yesterday_open_cases": 0.014564678824917632,
    "today_vs_yesterday_recovered": 0.00674899660543371,
    "yesterday_confirmed": 56159507,
    "yesterday_deaths": 1348179,
    "yesterday_open_cases": 18808791,
    "yesterday_recovered": 36002537
  },
  "updated_at": "2020-11-19 21:34UTC"
}

How I should build a model so that this property would be changed every day? (of course, this date needs to have a proper format "yyyy-MM-dd")


Solution

  • I would probably do:

    var dates: [String: YourModel]
    

    if it will potentially have multiple dates in that field.. otherwise, I'd probably do a custom object that overrides init(from decoder: and parses out that info