java - Modelmapper: Map an element in a list to field in POJO -


public class simpledto{     private string firstelement;     private string lastelement; }  public class complexsource{     private list<string> elementlist; } 

i tried map usingmap().setfirstelement(source.getelementlist().get(0)) error stating "1) invalid source method java.util.list.get(). ensure method has 0 parameters , not return void."

how map element in list field in pojo using modelmapper or other alternative?

in case can't use propertymap. if want map using modelmapper must use converter instead of propertymap have done.

first converter next source complexsource , simpledto destination:

converter<complexsource, simpledto> converter = new abstractconverter<complexsource, simpledto>() {     @override     protected simpledto convert(complexsource source) {         simpledto destination = new simpledto();         list<string> sourcelist = source.getelementlist();          if(null != sourcelist && !sourcelist.isempty()){             int sizelist = sourcelist.size();              destination.setfirstelement(sourcelist.get(0));             destination.setlastelement(sourcelist.get(sizelist - 1));         }          return destination;     } }; 

then need add converter modelmapper instance:

modelmapper mapper = new modelmapper(); mapper.addconverter(converter); 

if try map, works perfectly:

complexsource complexsource = new complexsource(); complexsource.setelementlist(arrays.aslist("firstelement", "lastelement"));  simpledto simpledto = mapper.map(complexsource, simpledto.class); system.out.println(simpledto); 

output

simpledto [firstelement=firstelement, lastelement=lastelement]


respect comment, need check nulls if need in source instance (in case possible null pointer if list null). inits destination instance, can configure destination instance how want provider (providers documentation).

in cases of special use cases this, need worry null checks , exceptions handling because converter way of modelmapper map manually pojos.

the advantadges of use modelmapper explained in web:

  • if configure correctly in cases no need map manually.
  • it centralizes mapping.
  • it provides mapping api handling special use cases. (this case)
  • and on (take web)

Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -