Search code examples
javadozer

Mapping a String to a Map via Dozer


I have a class, let's call it A with a Map field, which is converted to class B which I use for database storage/retrieval in which that field is mapped to a String. The mapping works when going from A to B perfectly. However, when going from B to A, I get a IllegalArgument exception which says that it cannot covert a String into a Map. Confuses me because Dozer's documentation says that this does work where it says:

Data type coversion is performed automatically by the Dozer mapping engine. Currently, Dozer supports the following types of conversions: (these are all bi-directional)

And then it goes on to list String to Map as one of the possible things.

What am I missing here, or what do I need to do special? My files look like:

public class ClassA {
  Map<String, String> field;

  public Map<String, String> getField() {
      return field;
  }
  public void setField(
          Map<String, String> field) {
      this.field = field;
  }
}

public class ClassB {
  String field;

  public String getField() {
      return field;
  }
  public void setField(String field) {
      this.field = field;
  }
}

<mapping>
    <class-a>com.fake.company.name.ClassA</class-a>
    <class-b>com.fake.company.name.ClassB</class-b>
</mapping>

Solution

  • From Map Based Properties section (classes used in documentation) it seems that explicitly mapping the fields is required because the field name will be used as a key for the map.

    <mapping>
      <class-a>com.fake.company.name.ClassA</class-a>
      <class-b>com.fake.company.name.ClassB</class-b>    
      <field>
        <a>field</a>
        <b>field</b>
      </field>
    </mapping>   
    

    You can use different value for the key like so

    <a key="someKeyValue">field</a>
    

    However, if your map has several key-value pairs, you probably need a custom converter (see here for details) because otherwise Dozer has no idea how to reconstruct the original map from the string.