有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java modelmapper空值跳过

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

在我的例子中,字符串b可能带有空值。我的modelmapper配置如下所示:

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

当我映射对象时,我得到b=null值的目标对象

试图远离此处显示的策略:SO- Question

我错过了什么


共 (3) 个答案

  1. # 1 楼答案

    您是否尝试过此配置:

    modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());
    
  2. # 2 楼答案

    我宁愿这样:

    @Configuration
    public class ModelMapperConfig {
    
        @Bean
        public ModelMapper modelMapper() {
            ModelMapper modelMapper = new ModelMapper();
            modelMapper.getConfiguration().setSkipNullEnabled(true);
    
            return modelMapper;
        }
    }
    
  3. # 3 楼答案

    看来这是不可能的

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

    我用下一个包装函数解决了这个问题

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

    也检查这个问题Modelmapper: How to apply custom mapping when source object is null?