Search code examples
javadozer

Dozer API Date Mapping config without XML


Anyone know how to convert the following into the api call format for Dozer? The documentation on the Dozer mapping site is pretty slim when it comes to the java mappings.

   <mappings>
  <configuration>
    <date-format>MM/dd/yyyy HH:mm</date-format>
  </configuration>

  <mapping wildcard="true">
    <class-a>org.dozer.vo.TestObject</class-a>
    <class-b>org.dozer.vo.TestObjectPrime</class-b>
    <field>
      <a>dateString</a>
      <b>dateObject</b>
    </field>
  </mapping>
  <mapping>
    <class-a>org.dozer.vo.SomeObject</class-a>
    <class-b>org.dozer.vo.SomeOtherObject</class-b>
    <field>
      <a>srcField</a>
      <b>destField</b>
    </field>
  </mapping>
</mappings>

Solution

  • As of version 5.5.1 of Dozer, API syntax cannot perform all mappings. The <configuration> element in your mapping can only be done with XML.

    If you can accept a version that bypasses the <configuration> limitation by adding some duplication, then the API mapping below should match your XML mapping:

    BeanMappingBuilder mappingBuilder = new BeanMappingBuilder() {
        @Override
        protected void configure() {
    
            String dateFormat = "MM/dd/yyyy HH:mm";
    
            mapping(TestObject.class, TestObjectPrime.class,
                    TypeMappingOptions.wildcard(true),
                    TypeMappingOptions.dateFormat(dateFormat))
                    .fields("dateString", "dateObject");
    
            mapping(SomeObject.class, SomeOtherObject.class,
                    TypeMappingOptions.dateFormat(dateFormat))
                    .fields("srcField", "destField");
        }
    };
    
    DozerBeanMapper apiBeanMapper = new DozerBeanMapper();
    apiBeanMapper.addMapping(mappingBuilder);
    

    If you're interested in further details, I've added a simple ApiAndXmlMappingTest example to PasteBin.