Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map String values to a String list using Dozer?

Hi I try to map following Source class in to following Destination class. I used following mapping in order to map string values in to the list string. It isn't mapping properly. I need to know how to map 2 string values into one destination string list using Dozer.

public class SourceClass {

  protected String streetName;
  protected String additionalStreetName;

}

public class Destination {

protected List<String> addressLine;

}

<mapping map-id="newId" >
<class-a>myPackage.SourceClass </class-a>
<class-b>myPackage.Destination</class-b> 

  <field>
    <a>streetName</a>
    <b>addressLine[0]</b>
  </field>
   <field>
    <a>additionalStreetName</a>
    <b>addressLine[1]</b>
  </field> 
</mapping> 
like image 845
Miraj Hamid Avatar asked Jan 31 '26 01:01

Miraj Hamid


2 Answers

Just specify type of objects in the destination list by Hint tag to let Dozer know what type of objects you want created in the destination list:

<field>
    <a>streetName</a>
    <b>addressLine[0]</b>
    <b-hint>java.lang.String</b-hint>
</field>
<field>
    <a>additionalStreetName</a>
    <b>addressLine[1]</b>
    <b-hint>java.lang.String</b-hint>
</field>

No custom converters are required.

like image 170
A.Panzer Avatar answered Feb 02 '26 15:02

A.Panzer


In order to do this you'll need to use a custom converter.

The documentation will give you a more thorough understanding but essentially, at the moment dozer has no idea how to convert a string into a list, so you have to tell it.

Your custom converter will take a String value as source and have a List as destination and will add the string it received into the list.

Something along the lines of this:

public class TestCustomConverter extends DozerConverter {

    public NewDozerConverter() {
        super(String.class, List.class);
    }

    public List<String> convertTo(String source, List<String> destination) {
        if (source == null) {
            return new ArrayList<>();
        }
        if (destination == null) {
            destination = new ArrayList<>();
        }

        destination.add(source);

        return destination;
    }

    public String convertFrom(List<String> source, String destination {
        return null;
    }
}

Your mappings will then look something like this:

<mapping map-id="newId" >
  <class-a>myPackage.SourceClass </class-a>
  <class-b>myPackage.Destination</class-b> 

  <field custom-converter="TestCustomConverter">
    <a>streetName</a>
    <b>addressLine</b>
  </field>
  <field custom-converter="TestCustomConverter">
    <a>additionalStreetName</a>
    <b>addressLine</b>
  </field> 
</mapping> 
like image 29
Kialandei Avatar answered Feb 02 '26 16:02

Kialandei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!