Parsing JSON with Swift Structures

I am new to working with JSON and Swift. This is the JSON object I am trying to parse.

{
"diet_duration":20,
"week_diet_data":{
"thursday":[ ... ],
"wednesday":[ ... ],
"monday":[
{
"food":"Warm honey and water",
"meal_time":"07:00"},
{
"food":"proper thali",
"meal_time":"15:00"}]}
}

This is my Swift file for the decoding the JSON.

class AllData : Codable {
  let diet_duration : Int
  let week_diet_data : Week

  init (diet_duration : Int, week_diet_data : Week) {
    self .diet_duration = diet_duration
    self .week_diet_data = week_diet_data
  }
}

class Week : Codable {
  let monday : [Day]
  let wednesday : [Day]
  let thursday : [Day]

  init (monday: [Day], wednesday: [Day], thursday: [Day]) {
    self .monday = monday
    self .wednesday = wednesday
    self .thursday = thursday
  }
}

class Day : Codable {
  let food : String
  let meal_time : String

  init (food: String, meal_time: String) {
    self .food = food
    self .meal_time = meal_time
  }
}

I wanted to know if it the class structure was correct or incorrect.

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
        }
    }
}
Terms of Service

Privacy Policy

Cookie Policy