如何根据containsKey将值映射到对象?

问题描述 投票:2回答:1

我有一个像这样的值的地图:

Map<String, Object> values = Map.of("name", "myName", "address", null);

我想更新这样的对象:

class User {
  String name;
  String address;
  String country;
}

现在我希望只有在源地图定义了键时才会覆盖User中的字段。所以address字段应设置为null(因为有一个显式映射为null),但不应更改country字段(因为地图中没有"country"键)。

这类似于nullValuePropertyMappingStrategy = IGNORE所做的,但并不完全,因为检查是map.containsKey检查而不是标准的空检查。

我可以扩展MapStruct以便它可以做到这一点吗?

我的MapStruct代码:

@Mapper
interface MyMapper {
    @Mapping(target = "name", expression = "java( from.getMap().get(\"name\") )")
    @Mapping(target = "address", expression = "java( from.getMap().get(\"address\") )")
    @Mapping(target = "country", expression = "java( from.getMap().get(\"country\") )")
    To get(MapWrapper from, @MappingTarget To to);
}
java mapstruct
1个回答
2
投票

MapStruct不能开箱即用。

但是,您可以将Map包装到Bean中。所以像这样:

public class MapAccessor{

private Map<String, Object> mappings;

   public MapAccessor(Map<String, Object> mappings) {
      this.mappings = mappings;
   }

   public Object getAddress(){
       return this.mappings.get("address");
   }

   public boolean hasAddress(){
       return this.mappings.containsKey("address");
   }
   ... 
}

然后你可以将一个普通的映射器映射到你的targetbean并使用WrappedMap来映射NullValuePropertyMappingStrategy

注意:你的映射器比它简单得多..


@Mapper( nullValuePropertyMappingStrategy = NullValueProperertyMappingStrategy.IGNORE )
interface MyMapper {

    To get(MapAccessor from, @MappingTarget To to);
}

© www.soinside.com 2019 - 2024. All rights reserved.