SledgeHammer
SledgeHammer

Reputation: 7690

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.

Upvotes: 1

Views: 695

Answers (2)

pirho
pirho

Reputation: 12215

I am not quite sure what you are trying to avoid with this:

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.

If you need to map the whole "pojo" or need to map just one field, create a converter like:

Converter<HasListOfPojos, HasOnePojo> x = new Converter<>() {
    ModelMapper mm2 = new ModelMapper();
    @Override
    public HasOnePojo convert(MappingContext<HasListOfPojos, HasOnePojo> context) {
        // do not create a new mm2 and do this mapping if no need for other
        // fields, just create a new "hop"
        HasOnePojo hop = mm2.map(context.getSource(), HasOnePojo.class);
        // here goes the get(0) mapping
        hop.setGoal(context.getSource().getGoals().get(0));
        return hop;
    }
};

Upvotes: 0

ldz
ldz

Reputation: 2215

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);

Upvotes: 1

Related Questions