How to map a card to a list

I am working on a project where I need to map a hierarchical Map<String, Object> , where the second parameter String or Map<String, Object> is expected. ModelMapper has worked amazingly so far, but I am having problems with a specific conversion. Given the following, where Model is just a marker interface:

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

Assuming Organization implements my Model token interface, 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 short: how can I get ModelMapper to remove map keys and use only the list of values ​​when clicked in the organizations property? Otherwise, the organization property becomes empty. You can assume that I have a good reason for this, and a bad example!

Thank you in advance for your entry!

Edit

I tried to build a Converter that would manage the conversion from Map to Collection<Model> 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:

  • Obviously, ModelMapper does not look at inheritance, therefore, when any Map implementation is specified as the source, the converter does not start. If, for example, I change the converter to receive a HashMap and pass the HashMap as a source, then it works.
  • context.getGenericDestinationType() returns List or Set classes without common information. How then does ModelMapper manage to create complex graphic models under normal circumstances?
+5
source share
1 answer

In your case, I think you can use an additional setter for the Pojo class. And then to convert maps to libraries using objects in ObjectMapper / BeanUtils / .... For example:

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

Source: https://habr.com/ru/post/1207905/


All Articles