modelmapper null value skip
Asked Answered
F

3

8
Class A {
    private String a;
    private String b;
    private B innerObject;
}
Class B {
    private String c;
}

In my case, String b might come in with a null value. My modelmapper configuration is like below:

ModelMapper mapper = new ModelMapper();
    mapper.getConfiguration()
    .setFieldMatchingEnabled(true)
    .setMatchingStrategy(MatchingStrategies.LOOSE)
    .setFieldAccessLevel(AccessLevel.PRIVATE)
    .setSkipNullEnabled(true)
    .setSourceNamingConvention(NamingConventions.JAVABEANS_MUTATOR);

when I map the object, I get the target object with b=null value.

Trying to stay away from a strategy shown here: SO- Question

What am I missing?

Fleam answered 14/12, 2017 at 17:14 Comment(1)
.setSkipNullEnabled(true) is enough, can you show me an example of your mapping?Trait
G
10

Have you tried this configuration:

modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());
Geelong answered 27/7, 2018 at 9:16 Comment(0)
K
7

I'd rather in this way:

@Configuration
public class ModelMapperConfig {

    @Bean
    public ModelMapper modelMapper() {
        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setSkipNullEnabled(true);

        return modelMapper;
    }
}
Koehn answered 24/6, 2020 at 17:47 Comment(2)
How can I make this work for only one specific mapping? Only when mapping class A to class B, I want this to be enabled.Spherics
@ShubhamDhingra you can check this code, where there some mappings handling specific situations to DTO Objects .Koehn
S
1

Looks, like it's not possible.

public <D> D map(Object source, Class<D> destinationType) {
    Assert.notNull(source, "source");
    Assert.notNull(destinationType, "destinationType");
    return this.mapInternal(source, (Object)null, destinationType (String)null);
}

I solved it with next wrapper function.

private static <D> D map(Object source, Type destination) {
    return source == null ? null : mapper.map(source, destination);
}

Check this question too Modelmapper: How to apply custom mapping when source object is null?

Swenson answered 4/6, 2020 at 13:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.