drago
drago

Reputation: 1283

How to create a struct for dynamic codable Root in SwiftUI?

A similar question was asked here: Codable Handle dynamic key at root

However, the answer in the above question doesn't have much explanation so I don't understand it.

So my question:

I have an API that output this JSON response:

 {
        "category1": {
            "products": [{
                "title": "Love",
                "id": "120",
                "url": "https:",
                "details": "",
                "duration": "22.27",
                "category": "category1",
                "sub_category": "sub cat name",
                "date_added": "2018-11-12"

            }, {
                "title": "Love",
                "id": "120",
                "url": "https:",
                "details": "",
                "duration": "22.27",
                "category": "category1",
                "sub_category": "sub cat name",
                "date_added": "2018-11-12"

            }]
        },

        "category2": {
            "products": [{
                "title": "Love",
                "id": "120",
                "url": "https:",
                "details": "",
                "duration": "22.27",
                "category": "category2",
                "sub_category": "sub cat name",
                "date_added": "2018-11-12"

            }, {
                "title": "Love",
                "id": "120",
                "url": "https:",
                "details": "",
                "duration": "22.27",
                "category": "category2",
                "sub_category": "sub cat name",
                "date_added": "2018-11-12"

            }]
        }
    }

The category1, category2 etc are dynamic categories.

So I can't really create a struct like this:

// MARK: - Welcome
struct Welcome: Codable {
    let category1, category2: Category
}

// MARK: - Category
struct Category: Codable {
    let products: [Product]
}

Reason being that the category names are dynamic and they are at the Root.

is there a way to do this?

Upvotes: 0

Views: 232

Answers (2)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You only need

struct Category: Codable {
   let products: [Product]
}

with

let res = try JSONDecoder().decode([String:Category].self, from: data) 
print(res["category1"]?.products)
let names = Array(res.keys)
print(names)

Upvotes: 1

Dris
Dris

Reputation: 844

Simply just use as dictionary, like:

struct Welcome: Codable {
   let category:[String:[Category]] 
}
struct Category: Codable {
    let products: [Product]
}

Upvotes: 0

Related Questions