How to map from a Map to List

2.1k views Asked by At

I'm working on a project where I need to map from a hierarchical Map<String, Object> where the second parameter is expected to be a String or Map<String, Object>. Thus far, ModelMapper has worked awesome, but I'm having trouble with a specific conversion. Given the following, where Model is simply a marker interface:

class Client implements Model {
    String firstName;
    String lastName;
    List<Organization> organizations = new ArrayList<>();
}

Assuming Organization implements my marker interface Model but is otherwise arbitrarily structured, I would like to be able to map the following to Client:

Map source = new HashMap(){{
    put("firstName", "John"),
    put("lastName", "Smith"),
    put("organizations", new HashMap(){{
        put("0", new HashMap(){{
            put("id", "1234");
        }});
        put("abc", new HashMap(){{
            put("id", "5678");
        }});
    }});
}};

In summary: how might I go about having ModelMapper drop the map keys and use only the value list when pushing into the organizations property? Failing this, the organizations property comes up empty. You may assume that I have a good reason for wishing to do this, and a poor example!

Thanks in advance for your input!

Edit

I attempted to build a Converter that would manage converting from a Map to a Collection<Model> to no avail. Given:

new Converter<Map, Collection<DataTransportObject>>() {
    @Override
    public Set convert(MappingContext<Map, Collection<DataTransportObject>> context) {
        LOG.debug("Here");
        Set<DataTransportObject> result = new HashSet<>();
        return result;
    }
}

There are two problems with this:

  1. Apparently ModelMapper doesn't look at inheritance, therefore when any implementation of Map is given as the source, the converter is not run. If, for example, I change the converter to accept HashMap and pass a HashMap as the source, then it works.
  2. context.getGenericDestinationType() returns List or Set classes without the generic information. How then does ModelMapper manage to construct complex model graphs under normal circumstances?
1

There are 1 answers

4
Andrey Pushin On BEST ANSWER

In your case I think you can use additional setter for Pojo class. And then for convert map to object use libraries as ObjectMapper/BeanUtils/... . For example:

void setOranizations(Map<String, Organization> map) {
    this.organizations = map.values();
}