Convert Map to POJO

2

I have a map like the following: Map<MiObjeto, List<OtroObjeto>> and I want to convert it to a POJO that is defined in the following way:

public class UnObjetoMas {

private MiObjeto miObjeto;
private List<OtroObjeto> otrosObjetos;

    //Getters and setters

}

How could I make that conversion?

    
asked by gibran alexis moreno zuñiga 23.03.2017 в 00:56
source

2 answers

2

A complete map can not be converted to that POJO, in any case it could become a Collection, for example a List, for which you could do something like this:

List<UnObjetoMas> list = new ArrayList<>();

for(Map.Entry<MiObjeto, List<OtroObjeto>> e : mapa.entrySet()){
    list.add(new UnObjetoMas(e.getKey(),e.getValue()));
}
//suponiendo que existe un constructor en la clase UnObjetoMas
public UnObjetoMas(MiObjeto miobj,List<OtroObjeto> otros){
    this.miObjeto = miobj;
    this.otrosObjetos = otros;
}

To put it another way, your UnObjetoMas class represents an Entry of the Map but it is not designed to represent a complete Map. Greetings

    
answered by 23.03.2017 в 10:57
0

There are several options, one is through Jackson , using the class ObjectMapper and its method convertValue :

ObjectMapper mapper = new ObjectMapper(); 
MyPojo pojo = mapper.convertValue(myMap, UnObjetoMas.class);
    
answered by 23.03.2017 в 01:15