How to use modelMapper to convert nested classes
I think if you configure your ModelMapper as LOOSE or STANDARD it will do for you.
modelMapper = new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE);
Otherwhise you could try next:
You may create a converter like:
public class ListThingToThingDTOConverter implements Converter<List<Thing>, List<ThingDTO>> { @Override public List<ThingDTO> convert(MappingContext<List<Thing>, List<ThingDTO>> context) { List<Thing> source = context.getSource(); List<ThingDTO> output = new ArrayList<>(); ... //Convert programmatically List<Thing> to List<ThingDTO> ... return output; }}
Then customize a Mapping Thing to ThingDTO as next:
public class SourceToSourceDTOMap extends PropertyMap<Thing, ThingDTO> { @Override protected void configure(){ using(new ListThingToThingDTOConverter()).map(source.getThings()).setThings(null); }
Finally you must add SourceToSourceDTOMap to your ModelMapper as below:
modelMapper = new ModelMapper(); modelMapper.addMappings(new SourceToSourceDTOMap());
You can map like the below code by creating generics . link for reference
http://modelmapper.org/user-manual/generics/
imports :
import java.lang.reflect.Type;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
In your service or controller class:
ModelMapper modelMapper = new ModelMapper();
Type listType = new TypeToken<SourceDTO>(){}.getType();
SourceDTO sourceDTO = modelMapper.map(source,listType);