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:
- 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 acceptHashMap
and pass aHashMap
as the source, then it works. context.getGenericDestinationType()
returnsList
orSet
classes without the generic information. How then does ModelMapper manage to construct complex model graphs under normal circumstances?
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: