Reputation: 3134
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
?
Upvotes: 3
Views: 12791
Reputation: 685
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));
}
}
Upvotes: 3
Reputation: 18970
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?
Upvotes: 3