Is it possible to specify List indexes as optional in Orika?

703 views Asked by At

I'm trying to map an address object of one type to a simpler type using Orika but ran into an issue where I get an IndexOutOfBounds exception if my list does not have at least as many elements as I'm specifying in my mapper.

Here are my example objects:

public class SourceAddress {
    List<String> addressLines;
}

public class DestinationAddress {
    String address1;
    String address2;
    String address3;
}

Here is my mapper:

mapperFactory.getMapperFacade().map(SourceAddress.class, DestinationAddress.class)
    .field("addressLine[0]", "address1")
    .field("addressLine[1]", "address2")
    .field("addressLine[2]", "address3")
    .mapNulls(false)
    .byDefault()
    .register();

But in my example the list in the Source address only has two Strings. I would expect that there is a way to optionally map the address3 field but I can't seem to find an example in the Orika unit tests.

The output I get when I try to map and get an exception is:

Error occurred: java.lang.IndexOutOfBoundsException: Index: 2, Size: 2

Does anyone know if this is possible to achieve in a simple way or do I have to write a CustomMapper for this type?

1

There are 1 answers

2
user7528019 On

just create "a ConverterClass" :

public class NoopConverter extends CustomConverter<String, String> {

  @Override
  public String convert(String source, Type<? extends String> destinationType, MappingContext mappingContext) {
    return source;
  }
}

and in the Mapper :

 @Override
 public void configure(MapperFactory factory) { 

 factory.getConverterFactory()
        .registerConverter(new NoopConverter());

 factory.classMap (SourceAddress.class, DestinationAddress.class)
        .field("addressLine[0]", "address1")
        .field("addressLine[1]", "address2")
        .field("addressLine[2]", "address3")
        .byDefault()
        .register();
}