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

Jorn :

I have a map of values like so:

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

I want to update an object like this:

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

Now I want the fields in User to be overwritten only if the source map has the key defined. So the address field should be set to null (because there's an explicit mapping to null), but the country field should not be changed (because there's no "country" key in the map).

This is similar to what nullValuePropertyMappingStrategy = IGNORE does, but not quite, as the check is a map.containsKey check instead of a standard null check.

Can I extend MapStruct so it can do this?

My MapStruct code:

@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);
}
Sjaak :

MapStruct can't do this out of the box.

However, you could wrap your Map into a Bean. So something like this:

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

And then you could a normal mapper mapping WrappedMap to your targetbean and using the NullValuePropertyMappingStrategy..

Note: your mapper is a lot simpler than as well..


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

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=151468&siteId=1