Miguel Gomez
Miguel Gomez

Reputation: 107

Decoding Formatted JSON Date in SwiftUI

How can I access to the data in this JSON from this website https://corona.lmao.ninja/v2/historical/usacounties/florida?lastdays=1

{
    "province": "florida",
    "county": "bay",
    "timeline": {
      "cases": {
        "4/20/20": 57 //How can I name this line inside of struct Cases
      },
      "deaths": {
        "4/20/20": 2 
      }
    }
  }

This is the Decodable JSON in SwiftUI

struct Florida: Codable, Identifiable {
    let id = UUID()
    var county: String
    var timeline: Cases
}
struct Cases: Codable, Identifiable {
    let id = UUID()
    var cases: ?????
}

Upvotes: 0

Views: 157

Answers (2)

Chris
Chris

Reputation: 8091

i know, it is not a "real" solution, but just for THIS case - one time read...this would work: (and now you know at least how to name the case...)

struct WelcomeElement: Codable {
    let province: Province
    let county: String
    let timeline: Timeline
}

enum Province: String, Codable {
    case florida = "florida"
}

// MARK: - Timeline
struct Timeline: Codable {
    let cases, deaths: Cases
}

// MARK: - Cases
struct Cases: Codable {
    let the42120: Int

    enum CodingKeys: String, CodingKey {
        case the42120 = "4/21/20"
    }
}

typealias Welcome = [WelcomeElement]


struct ContentView: View {

    let dataArray : Welcome = []

    init() {

        let url = URL(string: "https://corona.lmao.ninja/v2/historical/usacounties/florida?lastdays=1")
        let request = URLRequest(url: url!)

        URLSession.shared.dataTask(with: request) { data, response, error in
            if let decodedResponse = try? JSONDecoder().decode(Welcome.self, from: data!) {

                print(decodedResponse)
            }

        }.resume()

    }

    var body: some View {
        Text("Hello, World!")
    }
}

a more general approach, if you change the lastdays to more days you can use:

// MARK: - WelcomeElement
struct WelcomeElement: Codable {
    let province: Province
    let county: String
    let timeline: Timeline
}

enum Province: String, Codable {
    case florida = "florida"
}

// MARK: - Timeline
struct Timeline: Codable {
    let cases, deaths: [String: Int]
}

typealias Welcome = [WelcomeElement]

but this works just for Florida...for a "general" approach i think you have to do it manually...so parse your answer from the server.

to be honest, the data which the server provides are not really helpful. if they would provide the date like this:

{ "date" : "18/07/18",
  "death" : 2
}

then it would be easy to read....so if you do not want to read it manually maybe you should search for a better server with a better service...

Upvotes: 1

Ishmeet
Ishmeet

Reputation: 705

var cases: [String: Int]

Cases is a dictionary. You cannot make it codable.

Upvotes: 1

Related Questions