LGTM. Note that JSONDecoder has a few keyDecodingStrategy-s that it can use to transform swift CodingKey (variable names in this case) to JSON key. You can just do
var weekDietData: ...
...
var dietDuration: ...
...
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
Note from the doc that it doesn’t do well with acronym. It should still be fine in this particular example.
Also, it seems those are more of a data storage, so I’d use struct, and let the rest be synthesized (initializers included)
struct AllData: Codable {
var dietDuration: Int, weekDietData: Week
}
struct Week: Codable {
var monday, wednesday, thursday: [Day]
}
struct Day: Codable {
var food, mealTime: String
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let result = try decoder.decode(AllData.self, from: data)
And you might also want to nest types where it makes sense.
struct AllData: Codable {
var dietDuration: Int, weekDietData: Week
struct Week: Codable {
var monday, wednesday, thursday: [Day]
struct Day: Codable {
var food, mealTime: String
}
}
}