Search code examples
javamodelmapper

ModelMapper flatten array property (get(0)) to String?


Src object has a property:

private List<Pojo> goals;

Dest object has a property

private String goal;

I want to map Src.goals.get(0).getName() -> Dest.goal. goals will always contain one item, but it has to be pulled in as a list because its coming from Neo4j.

I tried doing:

    userTypeMap.addMappings(mapper -> {
        mapper.map(src -> src.getGoals().get(0).getName(), UserDto::setGoal);
    });

But modelmapper didn't like the parameter. Then I tried:

    userTypeMap.addMappings(mapper -> {
        mapper.map(src -> src.getGoals(), UserDto::setGoal);
    });

And that gave me:

"goal": "[org.xxx.models.Goal@5e0b5bd8]",

I then tried to add a converter for List -> String, but that didn't get called. If I add a converter for the entire pojo to dto then I have to map the whole pojo which I don't want to do, I just want to override this one property.


Solution

  • You can wrap the List access in a Converter and use this in a PropertyMap like follows:

    ModelMapper mm = new ModelMapper();
    Converter<List<Pojo>, String> goalsToName = 
        ctx -> ctx.getSource() == null ? null : ctx.getSource().get(0).getName();
    PropertyMap<Src, Dest> propertyMap = new PropertyMap<>() {
        @Override
        protected void configure() {
            using(goalsToName).map(source.getGoals()).setGoal(null);
        }
    };
    mm.addMappings(propertyMap);