Home > Net >  Filter json to exclude value not in enum case
Filter json to exclude value not in enum case

Time:10-22

I have an API that returns

 {
  "data": [
    {
      "serviceName": "language",
      "date": "2020-01-29 15:00:52"
    },
    {
      "serviceName": "country",
      "date": "2020-02-27 10:16:34"
    },
    {
      "serviceName": "currency",
      "date": "2020-01-29 15:01:43"
    },
    {
      "serviceName": "category",
      "date": "2019-06-27 09:07:11"
    },
    {
      "serviceName": "installationProcedure",
      "date": "2020-01-28 12:42:50"
    },
    {
      "serviceName": "remote",
      "date": "2021-05-10 10:55:29"
    },
    {
      "serviceName": "accessory",
      "date": "2019-09-18 14:48:45"
    },
    {
      "serviceName": "interfaceFirmware",
      "date": "2021-05-04 13:57:08"
    },
    {
      "serviceName": "kit",
      "date": "2019-09-19 11:37:57"
    },
    {
      "serviceName": "product",
      "date": "2020-11-19 15:05:09"
    },
    {
      "serviceName": "installation",
      "date": "2021-10-15 18:20:15"
    },
    {
      "serviceName": "controlunit",
      "date": "2021-10-13 14:35:55"
    },
    {
      "serviceName": "radioreceiver",
      "date": "2021-06-10 10:57:14"
    },
    {
      "serviceName": "firmware",
      "date": "2021-05-04 13:57:08"
    },
    {
      "serviceName": "faqs",
      "date": "2019-09-18 15:02:05"
    },
    {
      "serviceName": "availableCountriesQuote",
      "date": "2019-10-03 09:57:56"
    }
  ]
}

and I want to decode it in ServicesList struct and I want to ignore all the items with serviceName not in my Service.Name enum.

I'm using Alamofire to call the API. In this way:

let jsonDecoder = JSONDecoder()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    jsonDecoder.dateDecodingStrategy = .formatted(dateFormatter)
    authSession.request(ConfigurationRouter.updateServices).validate().responseDecodable(of: ServicesList.self, decoder: jsonDecoder) {
...
}

but I obtain an error:

"Cannot initialize Name from invalid String value installation"

How can I achieve this?

struct ServicesList: Codable {
    let services: [Service]
}

extension ServicesList {
    enum CodingKeys: String, CodingKey {
        case services = "data"
    }
}

struct Service: Codable {
    let name: Name
    let date: Date
    
    enum Name: String, Codable {
        case language = "language"
        case country = "country"
        case currency = "currency"
        case category = "category"
        case installationProcedure = "installationProcedure"
        case remote = "remote"
        case accessory = "accessory"
        case kit = "kit"
        case product = "product"
        case firmwareFamily = "firmware"
        case controlUnitFAQ = "faqs"
        case countriesWithEnabledEstimates = "availableCountriesQuote"
        case interfaceFirmware = "interfaceFirmware"
    }
}

extension Service {
    enum CodingKeys: String, CodingKey {
        case name = "serviceName"
        case date
    }
}

CodePudding user response:

Just make Name enum to consume CaseIterable protocol like below:

enum Name: String, Codable, CaseIterable {
    case language = "language"
    case country = "country"
    case currency = "currency"
    case category = "category"
    case installationProcedure = "installationProcedure"
    case remote = "remote"
    case accessory = "accessory"
    case kit = "kit"
    case product = "product"
    case firmwareFamily = "firmware"
    case controlUnitFAQ = "faqs"
    case countriesWithEnabledEstimates = "availableCountriesQuote"
    case interfaceFirmware = "interfaceFirmware"
}

then use below line to filter services array:

services.filter{ Service.Name.allCases.contains( $0.name) }

CodePudding user response:

If you want to do this during the decoding it will need to be done in several steps, my solution first decodes each item in the array to a dictionary and then checks if a Service item can be initialized from that dictionary.

So first we need a custom failable init for Service

init?(name: String?, date: String?) {
    guard let date = date else { return nil }

    guard let name = name, let serviceName = Name(rawValue: name) else { return nil }
    self.name = serviceName
    self.date = date //Date conversion needed here, omitted 
}

and then we use it in a init(from:) in the ServiceList struct

init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    var nestedContainer = try container.nestedUnkeyedContainer(forKey: .services)
    var valid = [Service]()
    while !nestedContainer.isAtEnd {
        let temp = try nestedContainer.decode([String: String].self)
        if let service = Service(name: temp["serviceName"], date: temp["date"]) {
            valid.append(service)
        }
    }
    services = valid
}
  • Related