How could I use a HashMap<String, Object>
as source to an object?
Here is my target object:
public class ComponentStyleDTO{
private String attribute;
private Object value;
}
I've tried to use this approach that I found and that is also in the documentation, but it's failing for me.
My Mapper:
@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);
}
My Util:
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;
}
}
}
And here's how I'm using this:
HashMap<String, Object> hmap = new HashMap<String, Object>();
hmap.put(attr.getKey(), attr.getValue());
ComponentStyleDTO componentDTO = componentStyleMapper.hashMapToComponentStyleDTO(hmap);
But it's returning me empty in attribute and value. Any idea of what I could be doing wrong?