Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use different coding keys for encoding/decoding in Swift

I have to decode an object from this JSON:

{
  "id": "..."
  "someData": { ... },
  "elements": {
    "values": [
      {
        "id": "1",
        ...
      },
      {
        "id": "2"",
        ...
      }
    ]
  }
}

So I have several structs like this:

struct Object: Codable {
  let id: String
  let someData: SomeCodableObject
  let elements: Elements
}

struct Elements: Codable {
  let values: [Value]
}

struct Value: Codable {
  let id: String
  ...
}

After filling each element with some data I've to send an object similar to the decoded one but changing "elements" and "values" by "elementQuotes" and "valueQuotes" respectively (yes, I know the API should avoid this weird behavior, but it's not possible...), that is, a JSON like this:

{
  "id": "..."
  "someData": { ... },
  "elementQuotes": {
    "valueQuotes": [
      {
        "id": "1",
        ...
      },
      {
        "id": "2"",
        ...
      }
    ]
  }
}

Is there any way to achieve this without using different objects (some for decoding and some other for encoding). That is, is there any way to specify different coding keys string values for encoding/decoding

I repeat: I know this is a really bad practice in the API side but ... I've to manage this "feature"

like image 726
rai212 Avatar asked May 20 '26 13:05

rai212


2 Answers

An easy way to encode different keys is to specify a custom keyEncodingStrategy.

let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .custom { keys in
    switch keys.last!.stringValue {
        case "elements": return AnyKey(stringValue: "elementQuotes")!
        case "values": return AnyKey(stringValue: "valueQuotes")!
        default: return keys.last!
            
    }
}

This requires also an extra struct AnyKey

struct AnyKey: CodingKey {
    var stringValue: String
    var intValue: Int?
    
    init?(stringValue: String) { self.stringValue = stringValue }
    init?(intValue: Int) {
        self.stringValue = String(intValue)
        self.intValue = intValue
    }
}

You can add as many cases as you like in the switch expression

like image 91
vadian Avatar answered May 23 '26 16:05

vadian


You can try to write a custom init decoder

struct Root: Decodable {
  let id: String
  let someData: String
  let elements: Elements
    
    enum CodingKeys: String, CodingKey {
        case id, someData, elements
        case elementQuotes
    }
    
    init(from decoder: Decoder) throws {

        let container = try decoder.container(keyedBy: CodingKeys.self)
        id =  try container.decode(String.self, forKey: .id)
        someData = try container.decode(String.self, forKey: .someData)
        do {
            elements = try container.decode(Elements.self, forKey: .elements)
        }
        catch {
            elements =  try container.decode(Elements.self, forKey: .elementQuotes)
        }
    }
}

struct Elements: Decodable {
  let values: [Value]
    
    enum CodingKeys: String, CodingKey {
        case values
        case valuesQuotes
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        do {
            values = try container.decode([Value].self, forKey: .values)
        }
        catch {
            values =  try container.decode([Value].self, forKey: .valuesQuotes)
        }
    }
}

struct Value: Codable {
  let id: String
}
like image 36
Sh_Khan Avatar answered May 23 '26 16:05

Sh_Khan