newtoMobileDev
newtoMobileDev

Reputation: 47

Need help decoding Json that contains an array

I need to do the following : Define two Swift classes to decode the JSON string

Decode the JSON string to get the objects of the two classes

This is the JSON I have to decode :

{“status":200,"holidays":[{"name":"Thanksgiving","date":"2017-10-09","observed":"2017-10-09","public":false}]}

I have tried creating two classes already and all I get back is nothing when calling the class in the main class

class HolidayItems : Decodable {

    let name : String?
    let date : String?
    let observed: String?
    let `public` : Bool?


    private enum CodingKeys: String, CodingKey {

        case name
        case date
        case observed
        case `public`

    }

    required init(from decoder:Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
        date = try container.decode(String.self, forKey: .date)
        observed = try container.decode(String.self, forKey: .observed)
        `public`  = try container.decode(Bool.self, forKey: .`public`)
    }

    } // HolidayItems

    class HolidayAPI: Decodable {

    let status: HolidayItems

    // let holiday :[HolidayItems]


    func getHolidayName() -> String {
        return status.name ?? "no advice, server problem"
    }
    func getAdviceNo() -> String {
        return status.date ?? ""
    }
    private enum CodingKeys: String, CodingKey {
        case status
        case holiday = "items"
    }

    required init(from decoder:Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        status = try container.decode(HolidayItems.self, forKey: .status)
      //  holiday = try container.decode(HolidayItems.self, forKey: .holiday)

    }
}

This is the result I'm suppose to get :

Optional("Thanksgiving") Optional("2017-10-09")

and I get nothing in return

Upvotes: 0

Views: 52

Answers (1)

Robert Dresler
Robert Dresler

Reputation: 11140

Your response is on root level just object with status of type Int and one array of another objects


Note

  • you don't have to implement your custom CodingKey
  • you don't need custom init with Decoder
  • you can have struct for your models
  • you can rename HolidayItems to Holiday

struct HolidayAPI: Decodable {
    let status: Int
    let holidays: [Holiday]
}

struct Holiday: Decodable {
    let name, date, observed: String
    let `public`: Bool
}

Then when you need to get certain holiday item, just get certain element of holidays

decodedResponse.holidays[0].name

Upvotes: 1

Related Questions