JSON Nested Arrays through SwiftUI NavigationLinks

Viewed 45

To start, full disclosure: I'm convinced that there is likely to be a simple solution to my problem, and if this is the case I apologise, however after 3 days of reading numerous articles and watching countless YouTube videos I'm getting no where, so I'm admitting defeat and reaching out...

Essentially, I'm wanting to use SwiftUI's NavigationView/Link to drill down 4 views using Data from my local JSON file. This app will mirror a typical shopping menu whereby the first 3 views will start with a main category, then drill into sub-categories before reaching the final (4th) screen - a detail view containing all the details about the chosen product (make, model, product code...)

I have so far learnt to construct the JSON data model before building structs to represent that data, binding them through Decodable -

JSON Code

{
"appliances": [{
        "id": 1,
        "title": "Washing Machines",
        "machines": [{
                "make": "Samsung",
                "model": "Series 5 ecobubble",
                "code": 645266
            },
            {
                "make": "AEG",
                "model": "Soft Water L9FEC966R",
                "code": 674801
            },
            {
                "make": "BOSCH",
                "model": "Serie 4 WAN28281GB",
                "code": 630539
            }
        ]
    },
    {
        "id": 2,
        "title": "Washer Dryers",
        "machines": [{
                "make": "HAIER",
                "model": "i-Pro Series 7 HWD100-B14979S",
                "code": 633616
            },
            {
                "make": "HISENSE",
                "model": "WDQY9014EVJM",
                "code": 677089
            }
        ]
    }
]

}

Model Data

struct Appliances: Decodable {
    let appliances: [Appliance]
}

struct Appliance: Decodable, Identifiable {
    let id: Int
    let title: String
    let machines: [Machine]
}

struct Machine: Decodable {
    let make: String
    let model: String
    let code: Int
}

let appliances: Appliances = load("jsonAppliances.json")

func load<T: Decodable>(_ file: String) -> T {
    guard let jsonPath = Bundle.main.url(forResource: file, withExtension: nil)   else {
    fatalError("error getting file path")
}

guard let jsonData = try? Data(contentsOf: jsonPath) else {
    fatalError("Error generating Data object")
}

let decoder = JSONDecoder()
do {
    let appliances = try decoder.decode(T.self, from: jsonData)
    return appliances
} catch {
    fatalError("Error decoding json")
}

}

I'm hoping (praying) that someone can point out a sensible way to achieve this and save my overall mental state from the freefall its experienced these past few days.

Thanks in advance,

Simon

0 Answers
Related