简体   繁体   中英

How to map a bean into a java.util.Map using MapStruct?

I'd like to map the fields of a bean class into a dictionary-like class, using MapStruct . My source class is a standard bean (simplified example):

public class Bean {
    private String a;
    private String b;

    public String getA() {
        return a;
    }

    public void setA(String a) {
        this.a = a;
    }

    public String getB() {
        return b;
    }

    public void setB(String b) {
        this.b = b;
    }
}

Now I want to map these fields into a Map-like container:

public class Dict {

    public enum Tag {
        A,
        B
    }

    private Map<Tag, String> dict = new HashMap<>();

    public String getEntry(Tag tag) {
        return dict.get(tag);
    }

    public void setEntry(Tag tag, String s) {
        dict.put(tag, s);
    }
}

In other words, I'd like MapStruct to generate something along the lines of:

    target.setEntry(Dict.Tag.A, source.getA());
    target.setEntry(Dict.Tag.B, source.getB());

I couldn't find anything similar in the MapStruct documentation . There is much flexibility for getting at mapping sources (nested sources, expressions), but for targets I can see only the target = "propertyname" notation which doesn't leave much room for flexibility.

What is the best solution to map into a java.util.Map ?

This kind of mapping is currently not supported in MapStruct. We thought about it before but didn't yet get to implementing it. Could you open a ticket in our issue tracker ?

You can use Jackson object mapper in your MapStruct mapper for convert object to Map.

@Mapper
public interface ModelMapper {

  ObjectMapper OBJECT_MAPPER = new ObjectMapper();

  default HashMap<String, Object> toMap(Object filter) {
    TypeFactory typeFactory = OBJECT_MAPPER.getTypeFactory();
    return OBJECT_MAPPER.convertValue(filter, typeFactory.constructMapType(Map.class, String.class, Object.class));
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM