Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func caseInsensitiveKeys() {
- struct Model: Codable, Equatable {
- let number: String?
- let id: String?
- let address: String?
- enum CodingKeys: String, CodingKey, CaseIterable {
- case number = "A-Number"
- case id = "A-Id"
- case address = "AddressId"
- }
- }
- let jsonStr = """
- [{
- "A-Number" : "12",
- "A-Id" : "1",
- "AddressId" : "23"
- },
- {
- "a-number" : "45",
- "a-id" : "2",
- "addressid" : "67"
- }]
- """
- do {
- let decoder = JSONDecoder()
- decoder.keyDecodingStrategy = .custom({ codingPath in
- let lastCodingPath = codingPath.last!
- let match = Model.CodingKeys.allCases.first { $0.rawValue.compare(lastCodingPath.stringValue, options: .caseInsensitive) == .orderedSame }
- return match ?? lastCodingPath
- })
- let models = try decoder.decode([Model].self, from: Data(jsonStr.utf8))
- print(models)
- } catch {
- print("Error case insentive keys: \(error)")
- }
- }
- caseInsensitiveKeys()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement