-1

How can I make a struct or class to decode following type of json structure in swift? I want to extract mainly the report node data !

{
    "earliest": "2020-10-17",
    "latest": "2020-10-28",
    "report": {
        "purchase": {
            "total": 1458600.0,
            "average": 121550.0,
            "min": 600000.0,
            "max": 1600.0
        },
        "sale": {
            "total": 434250.0,
            "average": 144750.0,
            "min": 360000.0,
            "max": 29250.0
        },
        "production": {
            "total": 792030,
            "average": 20308.46153846154,
            "min": 12000,
            "max": 29700
        }
    }
}
ios coder
  • 1
  • 4
  • 31
  • 91
  • 1
    There are plenty of tutorials for this on youtube, if you google "Encode Decode JSON in swift", you should be able to find an answer pretty easily – jlmurph Nov 28 '20 at 22:49

1 Answers1

1

You just need to structure your data and conform it to Codable:

struct Root: Codable {
    let earliest: String
    let latest: String
    let report: Report
}

struct Report: Codable {
    let purchase: Results
    let sale: Results
    let production: Results
}

struct Results: Codable {
    let total: Int
    let average: Double
    let min: Int
    let max: Int
}

let json = """
{
    "earliest": "2020-10-17",
    "latest": "2020-10-28",
    "report": {
        "purchase": {
            "total": 1458600.0,
            "average": 121550.0,
            "min": 600000.0,
            "max": 1600.0
        },
        "sale": {
            "total": 434250.0,
            "average": 144750.0,
            "min": 360000.0,
            "max": 29250.0
        },
        "production": {
            "total": 792030,
            "average": 20308.46153846154,
            "min": 12000,
            "max": 29700
        }
    }
}
"""

do {
    let report = try JSONDecoder().decode(Root.self, from: .init(json.utf8)).report
    print("report", report)
} catch {
   print(error)
}

report Report(purchase: Results(total: 1458600, average: 121550.0, min: 600000, max: 1600), sale: Results(total: 434250, average: 144750.0, min: 360000, max: 29250), production: Results(total: 792030, average: 20308.46153846154, min: 12000, max: 29700))

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • 1
    Hey thanks for your answer. Actually I was doing the exact same thing until I realized that it was not getting parsed because inside 'purchase' and 'sale' node the values of 'total', 'min','max' are in "Double" whereas in 'production' node it is in "Int". Seems super stupid but unfortunately that is how swift works (smh). Thanks for your help again! – Jatin Menghani Nov 29 '20 at 08:29