Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

248
Visualizações
How to map dictionary with dynamic keys with ObjectMapper?

I'm new to ObjectMapper. I have response from the server:

{
      "123123": 10,
      "435555": 2,
      "435333": 8,
      "567567": 4
}

Keys (dynamic) are going to be IDs. Values are going to be COUNT. How can I map it with ObjectMapper?

My code isn't working because dynamic keys:

extension Item: Mappable {

    private static let kId = "id"
    private static let kCount = "count"

    public init?(map: Map) {
        self.init()
    }

    mutating public func mapping(map: Map) {

        id <- map[Item.kId]
        count <- map[Item.kCount]
    }
}
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Your response is an object and you can access it via map.JSON, and its type is [String: Any]. Then you can use that like a normal Dictionary.

Here I create a class named Model that has array of items (of type Item) and in func mapping(:Map) I mapped map.JSON elements to Item.

class Model: Mappable {
    typealias Item = (id: String, count: Int)
    var items: [Item] = []

    required init?(map: Map) {

    }

    func mapping(map: Map) {
        let rawDictionary = map.JSON
        let items = rawDictionary.compactMap { (key, value) -> Item? in
            guard let intValue = value as? Int else { return nil }
            return (key, intValue)
        }
        self.items = items
    }
}

let jsonString = """
{
    "123123": 10,
    "435555": 2,
    "435333": 8,
    "567567": 4
}
"""

let model = Model(JSONString: jsonString)
print(model?.items[0])  //Optional((id: "123123", count: 10))

over 4 years ago · Santiago Trujillo Relatório

0

You can try

 do{

    let res = try JSONDecoder().decode([String:Int].self, from: data)

}
catch {

    print(error)
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda