Search code examples
swiftalamofiredecodable

How to get any type array field from alamofire response?


I have such field in my json response:

"title": [2402, "Dr.", "Prof.", "Prof. Dr.", "HM"]

And I would like to parse it. I have my model class:

struct AppDataModel:Decodable {
    ...
    let title = Dictionary<String,Any>()
    
    
    enum CodingKeys: String,CodingKey{
        case title
        ...
    }
    ...
}

As you can see I tried to use Dictionary<String,Any>() for it. And also I thought about array of Any -> [Any] but I usually get such error:

Type 'AppDataModel' does not conform to protocol 'Decodable'

I think that I have to process it like an ordinary json. But I didn't find such data type in Swift, only dictionary. So, maybe someone knows how to process such response fields?


Solution

  • This is an example to decode a single key as heterogenous array

    let jsonString = """
    {"title": [2402, "Dr.", "Prof.", "Prof. Dr.", "HM"], "name":"Foo"}
    """
    
    struct AppDataModel : Decodable {
        let titles : [String]
        let name : String
        
        private enum CodingKeys: String, CodingKey { case title, name }
        
        init(from decoder: Decoder) throws {
            let container = try decoder.container(keyedBy: CodingKeys.self)
            var titlesContainer = try container.nestedUnkeyedContainer(forKey: .title)
            var titleArray = [String]()
            let _ = try titlesContainer.decode(Int.self) // decode and drop the leading integer
            while !titlesContainer.isAtEnd { // decode all following strings
                titleArray.append(try titlesContainer.decode(String.self))
            }
            titles = titleArray
            self.name = try container.decode(String.self, forKey: .name)
        }
    }
    
    let data = Data(jsonString.utf8)
    
    do {
        let result = try JSONDecoder().decode(AppDataModel.self, from: data)
        print(result)
    } catch {
        print(error)
    }