【问题标题】:How to use TypeMap in ModelMapper如何在 ModelMapper 中使用 TypeMap
【发布时间】:2021-11-18 01:45:57
【问题描述】:

我有一种情况,如果值为 null,则 json 有效负载会发生变化。

例如下面的日期对象有三个对象(年、月、日)。 如果没有像“day”这样的数据,“value”将不会显示,它将为空。

"date":{
  "year":{
     "value":"2021"
  },
  "month":{
     "value":"09"
  },
  "day":null
 }

我有一堆 if 条件来检查这些空值,但看起来不太好。

所以现在我正在研究使用 ModelMapper。

这是我目前所拥有的。我认为一些开箱即用的属性会 处理 null 但我想不会,因为 null 时有效负载会发生变化。

private static MyDto mapData(Info info) {

ModelMapper modelMapper = new ModelMapper();   // relace -- MyCustomizedMapper

modelMapper.getConfiguration()
.setMatchingStrategy(MatchingStrategies.STRICT)
.setDeepCopyEnabled(true)
.setPropertyCondition(Conditions.isNotNull());

var mappedDto = modelMapper.map(info, MyDto.class);
mappedDto.setDay(info.getDay().getValue());
}
return mappedDto 

//nullPointerException is thrown because getDay is null 

然后我尝试使用一个自定义的映射器来检查 null。

public class MyCustomizedMapper extends ModelMapper{

@Override
public <D> D map(Object source, Class<D> destinationType) {
 Object tmpSource = source;
  if(source == null){
  tmpSource = new Object();
  }
  return super.map(tmpSource, destinationType);
 }
}

但我仍然得到一个空指针异常。

我在模型映射器网站上遇到了这段代码,现在尝试使用 when(notNull) 条件。

  typeMap.addMappings(mapper -> mapper.when(notNull).map(Person::getName, PersonDTO::setName));

这里正在尝试使用 TypeMap...

TypeMap<Info, MyDto> typeMap =
    modelMapper.createTypeMap(Info.class, MyDto.class);

// Define the mappings on the type map
typeMap.addMappings(mapper -> {
  mapper.map(src -> src.getDay(),
      MyDto::setDay);
  mapper.when(Conditions.isNotNull()).skip(MyDto::setDay);
});

错误:条件跳过时必须提供源属性,请改用when().skip(sourceGetter,destinationSetter)

在这种情况下如何正确使用 ModelMapper?

【问题讨论】:

    标签: java json spring spring-boot modelmapper


    【解决方案1】:

    您只需将Conditional 映射配置为当isNotNull 条件匹配时仅应用

    TypeMap<Info, MyDto> typeMap = modelMapper.createTypeMap(Info.class, MyDto.class);
    typeMap.addMappings(mapper -> {
        mapper.when(Condition.isNotNull()).map(Info::getDay, MyDto::setDay);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多