arraysjsonswiftswift-structs

How to create a JSON that conforms to this Swift Struct


I'm really sorry if this is a bit of a dumb question but I was wondering how I could create a JSON and JSON Decoder that works with the Swift Struct below.

Thanks!

struct Example: Hashable, Codable, Identifiable {
    var id: Int
    var title: String
    var category: String
    var year: String
    var imageName: String
    var bannerName: String
    var URLScheme: String
    var isFavorite: Bool
    
    
    struct ProductRow: Codable, Hashable {
        let title: String
        let value: String
    }
    
    let rows: [ProductRow]
    
}

Solution

  • This can be achieved with some simple instructions.

    Output:

    {
        "category": "category",
        "id": 1,
        "URLScheme": "https",
        "title": "title",
        "isFavorite": true,
        "rows": [
            {
                "title": "title1",
                "value": "1"
            },
            {
                "title": "title2",
                "value": "2"
            }
        ],
        "year": "now",
        "bannerName": "banner",
        "imageName": "image"
    }