Home > Software design >  How to create a JSON that conforms to this Swift Struct
How to create a JSON that conforms to this Swift Struct

Time:08-12

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]
    
}

CodePudding user response:

This can be achieved with some simple instructions.

  • create an instance of your model:

    let example = Example(id: 1, title: "title", category: "category", 
        year: "now", imageName: "image", bannerName: "banner", URLScheme: "https", 
        isFavorite: true, rows: [.init(title: "title1", value: "1"),.init(title: "title2", value: "2")])
    
  • Then "encode" it with a JSONEncoder, convert everything to a String and print it:

    let json = try JSONEncoder().encode(example)
    print(String(data: json, encoding: .utf8)!)
    

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"
}

CodePudding user response:

There's 2 different models here, you'd need to decode them separately, but generally all you'd need to do is:

let decoder = JSONDecoder()
decoder.decode([ProductRow.self], from: data)

See more info here

Example Object: You should probably make year an Int

{
   "id": 1,
   "title" : "title here"
   "category": "category here"
   "year": "2022"
   "imageName": "imageName here"
   "bannerName" : "banner name here"
   "URLScheme" : "url scheme here"
   "isFavorite": false
}

Rows

{
   "rows" : {[
      {
         "title": "the title here",
         "value": "the value here",
      },
      {
         "title": "the title here",
         "value": "the value here",
      },
      {
         "title": "the title here",
         "value": "the value here",
      }
   ]}
}
  • Related