1

I have an API and I need to call, to get a list of holidays with some additional info along with it. The link of my API - http://mahindralylf.com/apiv1/getholidays

The structure I created using the website app.quicktype.io

struct Holiday: Codable {
    let responseCode, responseMsg: String
    let holidayCount: Int
    let holidays: [HolidayElement]

enum CodingKeys: String, CodingKey {
    case responseCode = "response_code"
    case responseMsg = "response_msg"
    case holidayCount = "holiday_count"
    case holidays
    }
}
struct HolidayElement: Codable {
    let month: String
    let image: String
    let details: [Detail]
}
struct Detail: Codable {
    let title, date, day: String
    let color: Color
}
enum Color: String, Codable {
    case b297Fe = "#B297FE"
    case e73838 = "#E73838"
    case the0D8464 = "#0D8464"
}

I can get to the "Holiday" object, print it, display my tableViewCells with a colour for the "holidayCount". What I want to do is, without using the normal json parsing and making my own arrays and dicts, to access the "Detail" for each "holidays".

tl;dr - I need to know how to access Detail for the holidays element

Thanks!!

2
  • You have a working solution but you don't. want to use it, have I understood you correctly? Commented Oct 6, 2018 at 8:25
  • Both holidays and details are arrays containing multiple items. Get an item by index or use a loop to iterate it. Commented Oct 6, 2018 at 8:35

1 Answer 1

1

Your data's coming back with an array of HolidayElements and each HolidayElement has an array of Details.

So for each HolidayElement, you'd want to get access to the details array. You'd do that like so:

let jsonResponse = try JSONDecoder().decode(Holiday.self, from: responseData)
print(jsonResponse.holidays[0].details)

Here's a repo to play around with.

Additionally, your coding keys are just converting from snake_case, so you don't really need them for that endpoint. Instead, you can just tell the decoder to convertFromSnakeCase

You can ditch the coding keys in this case and just decode as follows:

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let jsonResponse = try decoder.decode(Holiday.self, from: responseData)
print(jsonResponse.holidays[0].details)
Sign up to request clarification or add additional context in comments.

2 Comments

The ditching the coding keys is a elegant solution. Can I ask why and when would you do that, also why and when mould you not?
The JSONDecoder can convert from snake case for you, so there’s no need for coding keys if you’re not going to rename them. If you’re going to rename keys, you’d need CodingKeys

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.