首页 > 解决方案 > 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);

但它让我在属性和价值上都是空的。知道我可能做错了什么吗?

标签: javaspringmapstruct

解决方案


恕我直言,最好的方法是最简单的方法:

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

推荐阅读