java - Mapstruct:HashMap 作为 Object 的源
问题描述
我如何使用 aHashMap<String, Object>
作为对象的源?
这是我的目标对象:
public class ComponentStyleDTO{
private String attribute;
private Object value;
}
我尝试使用我发现的这种方法,这也在文档中,但它对我来说失败了。
我的映射器:
@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE, componentModel = "spring", uses = ComponentStyleMapperUtil.class)
public interface ComponentStyleMapper {
ComponentStyleMapper MAPPER = Mappers.getMapper(ComponentStyleMapper.class);
@Mappings({@Mapping(target = "attribute", qualifiedBy = ComponentStyleMapperUtil.Attribute.class),
@Mapping(target = "value", qualifiedBy = ComponentStyleMapperUtil.Value.class)})
ComponentStyleDTO hashMapToComponentStyleDTO(HashMap<String, Object> hashMap);
}
我的实用程序:
public class ComponentStyleMapperUtil{
@Qualifier
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Attribute {
}
@Qualifier
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Value {
}
@Attribute
public String attribute(HashMap<String, Object> in){
return (String) in.entrySet().stream().findFirst().get().getKey();
}
@Value
public Object value(HashMap<String, Object> in) {
Object value = in.entrySet().stream().findFirst().get().getValue();
if(value instanceof String){
return value;
}else if(value instanceof LinkedHashMap){
List<ComponentStyleDTO> childs = new ArrayList<ComponentStyleDTO>();
HashMap<String, Object> child = (HashMap<String, Object>) value;
for(String key: child.keySet()){
ComponentStyleDTO schild = new ComponentStyleDTO();
schild.setAttribute(key);
schild.setValue((String) child.get(key));
childs.add(schild);
}
return childs;
}else{
return value;
}
}
}
这就是我如何使用它:
HashMap<String, Object> hmap = new HashMap<String, Object>();
hmap.put(attr.getKey(), attr.getValue());
ComponentStyleDTO componentDTO = componentStyleMapper.hashMapToComponentStyleDTO(hmap);
但它让我在属性和价值上都是空的。知道我可能做错了什么吗?
解决方案
恕我直言,最好的方法是最简单的方法:
default ComponentStyleDTO hashMapToComponentStyleDTO(HashMap<String, Object> hashMap){
ComponentStyleDTO result = new ComponentStyleDTO();
result.setAtribute1(hashMap.get("atribute1"));
result.setAtribute2(hashMap.get("atribute2"));
result.setAtribute3(hashMap.get("atribute3"));
...
return result;
}
或者
default List<ComponentStyleDTO> hashMapToComponentStyleDTO(HashMap<String, Object> hashMap){
return hashMap.entrySet()
.stream()
.map(e -> new ComponentStyleDTO(e.getKey(), e.getValue()))
.collect(Collectors.toList());
}
推荐阅读
- node.js - 带有路由的 NodeJS 不会发布并返回 404 异常
- angular - 您能否在 tsconfig.spec.json 而不是 tsconfig.app.json 中为路径起别名,并让 VS Code 在规范中找到适当的路径?
- bash - 如何检测文本文件的列值是否未分组?
- c++ - 使用 gl_VertexID 计算顶点(在网格内)的 X 和 Z 位置
- java - 我如何使用 int 而不是使用 Integer?
- python-3.x - count(for in range) TypeError Python
- javascript - 为什么我的角度 kendo-timepicker 不显示按钮,直到我点击页面上的刷新?
- javascript - UTC 与 ISO 时间格式
- reactjs - 即使我正确设置了路径,React 也没有找到模块
- javascript - 电子,IPC 通信似乎无法正常工作