Advertisement
Larme

Untitled

May 16th, 2022
1,593
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.09 KB | None | 0 0
  1. func caseInsensitiveKeys() {
  2.     struct Model: Codable, Equatable {
  3.         let number: String?
  4.         let id: String?
  5.         let address: String?
  6.  
  7.         enum CodingKeys: String, CodingKey, CaseIterable {
  8.             case number = "A-Number"
  9.             case id = "A-Id"
  10.             case address = "AddressId"
  11.         }
  12.     }
  13.  
  14.     let jsonStr = """
  15.    [{
  16.    "A-Number" : "12",
  17.    "A-Id" : "1",
  18.    "AddressId" : "23"
  19.    },
  20.    {
  21.    "a-number" : "45",
  22.    "a-id" : "2",
  23.    "addressid" : "67"
  24.    }]
  25.    """
  26.  
  27.     do {
  28.         let decoder = JSONDecoder()
  29.         decoder.keyDecodingStrategy = .custom({ codingPath in
  30.             let lastCodingPath = codingPath.last!
  31.             let match = Model.CodingKeys.allCases.first { $0.rawValue.compare(lastCodingPath.stringValue, options: .caseInsensitive) == .orderedSame }
  32.             return match ?? lastCodingPath
  33.         })
  34.         let models = try decoder.decode([Model].self, from: Data(jsonStr.utf8))
  35.         print(models)
  36.     } catch {
  37.         print("Error case insentive keys: \(error)")
  38.     }
  39. }
  40.  
  41. caseInsensitiveKeys()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement