Dozer, how to convert a map to a list of complex types

1.6k views Asked by At

I am struggling with a Dozer mapping. I would like to convert a java.util.Map to a java.util.List<Code>. My classes are implemented as follows.

public class A {
   private List<Code> values;
}

class B {
   private Map<String, String> values;
}

class Code {
   private String key;
   private String value;

   // getter & setter ommitted
}

My mapping looks as follows.

<mapping wildcard="true">
    <class-a>A</class-a>
    <class-b>B</class-b>

    <field custom-converter="ABCustomConverter">
        <a>values</a>
        <b>values</b>
    </field>
</mapping>

The custom converter.

public class ABCustomConverter extends DozerConverter<List<Code>, Map<String, String>> {

     public ABCustomConverter () {
       super((Class<List<Code>>) (Class<?>) List.class, (Class<Map<String, String>>) (Class<?>) List.class);
     }

     @Override
     public Map<String, String> convertTo(List<Code> source, Map<String, String> destination) {
        throw new NotImplementedException();
     }

     @Override
     public List<Code> convertFrom(Map<String, String> source, List<Code> destination) {

        if (source == null) return null;

        List<Code> modelList = Lists.newArrayListWithCapacity(source.size());

        for (String key : source.keySet()) {
          Code model = new Code();
          model.setKey(key);
          model.setValue(source.get(key));

          modelList.add(model);
        }
        return modelList;
     }
}

My custom converter always receives a null value when convertForm is called. For some reason Dozer tries to get the key values from my java.util.Map and this results, as expected, in a null value that is forwarded to my custom converter. But I would like to get the whole map forwarded to my converter. Can someone explain me how to achieve this custom mapping?

1

There are 1 answers

0
saw303 On BEST ANSWER

The answer is to provide some hints for Dozer.

<mapping wildcard="true">
    <class-a>A</class-a>
    <class-b>B</class-b>

    <field custom-converter="ABCustomConverter">
        <a>values</a>
        <b>values</b>

        <a-hint>java.util.LinkedHashMap</a-hint>
        <b-hint>java.util.ArrayList</b-hint>
    </field>
</mapping>

Thank you for helping me out!