Search code examples
iosjsonswiftalamofirecodable

Swift decoding JSON which has two possible types for the same field


I am dealing with this JSON using Alamofire and Codable:

[
    {
        "pID": "37229890-dcd8-36c4-bb63-e7b174aafeb7",
        "type": "FIRST",
        "content": {
            "id": "ff64",
            "ret": {
                "name": "A",
                "logoUrl": "hpng"
            },
            "amo": {
                "value": 120.00,
                "currency": "EUR"
            },
            "s": {
                "value": 1.20,
                "currency": "EUR"
            },
            "datetime": "",
            "p": [
                {
                    "ti": "",
                    "pr": {
                        "value": 120.00,
                        "currency": "EUR"
                    },
                    "pic": "string"
                }
            ]
        }
    },
    {
        "pID": "37229890-dcd8-36c4-bb63-e7b174aafeb7",
        "type": "RATE",
        "content": "Rate this app"
    }
]

As you can see, te value of the type "content" can be a simple String or a Struct.

I have tried a custom decoder and having a top struct but I am not able to achieve a solution for this problem.

What is the best way to solve this problem?


Solution

  • Is this what you are expecting?

    let json = """
    [
        {
            "type": "type1",
            "content": {
                "id": "ff64",
                "title": "a title"
            }
        },
        {
            "type": "type2",
            "content": "Rate this app"
        }
    ]
    """
    
    struct Type1: Decodable {
      let id: String
      let title: String
    }
    
    typealias Type2 = String
    
    enum Content: Decodable {
      case type1(Type1)
      case type2(Type2)
    
      enum ContentType: String, Decodable {
        case type1
        case type2
      }
    
      enum Keys: String, CodingKey {
        case type
        case content
      }
    
      init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: Keys.self)
        let type = try container.decode(ContentType.self, forKey: .type)
    
        switch type {
        case .type1:
          let content = try container.decode(Type1.self, forKey: .content)
          self = .type1(content)
        case .type2:
          let content = try container.decode(Type2.self, forKey: .content)
          self = .type2(content)
        }
      }
    }
    
    let result = try JSONDecoder().decode([Content].self, from: json.data(using: .utf8)!)