[英]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 . 我想使用MapStruct将bean类的字段映射到类似字典的类中。 My source class is a standard bean (simplified example): 我的源类是标准Bean(简化示例):
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: 现在,我想将这些字段映射到类似Map的容器中:
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: 换句话说,我希望MapStruct生成类似于以下内容的内容:
target.setEntry(Dict.Tag.A, source.getA());
target.setEntry(Dict.Tag.B, source.getB());
I couldn't find anything similar in the MapStruct documentation . 我在MapStruct 文档中找不到任何类似的内容 。 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. 映射源(嵌套源,表达式)有很大的灵活性,但是对于目标,我只能看到target = "propertyname"
表示法,没有太多灵活性。
What is the best solution to map into a java.util.Map
? 映射到java.util.Map
的最佳解决方案是什么?
This kind of mapping is currently not supported in MapStruct. 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. 您可以在MapStruct映射器中使用Jackson对象映射器将对象转换为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));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.