2
votes

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?

2
with JMapper is very easy implement this mapping, however is out of scope for this thread, if you are interested open a new question with an explicit JMapper request or an issue on github - Alessandro
@Alessandro Last time we looked at JMapper it used bytecode enhancement to do the mapping. What I like about MapStruct is that it generates fast and easily debuggable code. - pesche

2 Answers

2
votes

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?

0
votes

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