【发布时间】:2019-02-08 22:13:18
【问题描述】:
如何使用HashMap<String, Object> 作为对象的源?
这是我的目标对象:
public class ComponentStyleDTO{
private String attribute;
private Object value;
}
我尝试使用我发现的 this 方法,该方法也在文档中,但对我来说失败了。
我的映射器:
@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);
但它让我在属性和价值上都是空的。知道我可能做错了什么吗?
【问题讨论】:
-
你在 DTO 上有 getter/setter(或 lombok 左右)吗?