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