【问题标题】:modelmapper null value skip模型映射器空值跳过
【发布时间】:2017-12-14 17:14:36
【问题描述】:
Class A {
    private String a;
    private String b;
    private B innerObject;
}
Class B {
    private String c;
}

在我的例子中,字符串 b 可能带有一个空值。我的模型映射器配置如下:

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

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

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

我错过了什么?

【问题讨论】:

  • .setSkipNullEnabled(true) 就够了,能给我看看你的映射示例吗?

标签: java null modelmapper


【解决方案1】:

你试过这个配置吗:

modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());

【讨论】:

    【解决方案2】:

    我宁愿这样:

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

    【讨论】:

      【解决方案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?

      【讨论】:

        猜你喜欢
        • 2018-02-16
        • 2014-11-08
        • 2022-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多