-1

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?

Andoni Da Silva
  • 1,161
  • 15
  • 31
  • 2
    Yep. Show us what you tried and how your Codable looks like + how are you trying to decode the json. – Teetz Aug 14 '20 at 09:32

2 Answers2

2

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)!)
congnd
  • 1,168
  • 8
  • 13
  • 1
    Yes!, I have solved the problem using a enum with associated types like this. Then when I have to access to the content value, I use a function inside the enum to return Any and I make a cast. Thanks – Andoni Da Silva Aug 14 '20 at 14:42
0

You can apply AnyCodable custom decoder approach that can decode your needed types e.g.:

struct AnyCodable : Codable {
    let value: Any
    
    func encode(to encoder: Encoder) throws {
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        
        if let str = try? container.decode(String.self) {
            value = str
        } else if let content = try? container.decode(Content.self) {
            value = content
        } else {
            throw DecodingError.dataCorruptedError(in: container, debugDescription: "Value cannot be decoded!")
        }
    }
}

struct Content : Codable {
    let id: String
}

struct Item : Codable {
    let content: AnyCodable
}

How to use:

do {
    let items = try JSONDecoder().decode([Item].self, from: json.data(using: .utf8)!);
    for item in items {
        if let content = item.content.value as? String {
            print(content)
        }
        else if let content = item.content.value as? Content {
            print(content.id)
        }
    }
}
catch {
    print(error)
}

iUrii
  • 11,742
  • 1
  • 33
  • 48