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

How to map values from map to object based on containsKey?

我有一个这样的值映射:

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 检查而不是标准的 null 检查。

我可以扩展 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);
}

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

然后你可以将法线映射器 WrappedMap 映射到你的目标 bean 并使用 NullValuePropertyMappingStrategy..

注意:您的映射器比 as 简单得多..


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

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