Search code examples
javadozer

Map only selected keys from HashMap to HashMap with Dozer


My goal is to map specific keys from HashMap to HashMap. I thought that 'key' attribute would help me. But i cannot make it work in expected way.

public class A {
  private Map<String, String> map = new HashMap<>();

  public A() {
    map.put("1", "a");
    map.put("2", "b");
    map.put("3", "c");
  }

  public Map<String, String> getMap() {
    return map;
  }

  public void setMap(Map<String, String> map) {
    this.map = map;
  }
}

public class B {
  private Map<String, String> map = new HashMap<String, String>();

  public B() {}

  public Map<String, String> getMap() {
    return map;
  }

  public void setMap(Map<String, String> map) {
    this.map = map;
  }
}

mapping.xml:
<mapping wildcard="false">
  <class-a>test.A</class-a>
  <class-b>test.B</class-b>
  <field>
    <a key="2">map</a>
    <b key="2">map</b>
  </field>
</mapping>

public static void main(String... args) {
  DozerBeanMapper mapper = new DozerBeanMapper(...);
  A a = new A();
  B b = mapper.map(a, B.class);
  System.out.println(b.getMap());
}

And result is {1=a, 2=b, 3=c}, but i want only {2=b}. How can i achieve that?


Solution

  • 'map-get-method' and 'map-set-method' attributes did the trick:

    <mapping wildcard="false">
      <class-a>test.A</class-a>
      <class-b>test.B</class-b>
      <field>
        <a map-get-method="get" key="2">map</a>
        <b map-set-method="put" key="2">map</b>
      </field>
    </mapping>