如何映射列表<a> to List<b> with Dozer?</b></a>

时间:2014-10-10 14:41:47

标签: list map dozer

我有一个服务,它会返回ListA个对象。 我想将其转换为List,例如B个对象。

我已经定义了从AB的映射。

天真,我试着做

List<A> ayes = ... // call to service
List<B> bees = dozerMapper.map(ayes, new ArrayList<B>().getClass());

但是,bees仍是ListA个对象。

我该怎么办?

1 个答案:

答案 0 :(得分:2)

我认为您可以使用提示http://dozer.sourceforge.net/documentation/collectionandarraymapping.html在Dozer中实现此目的,但我们发现在默认Mapper周围创建包装器更容易。一个例子如下。然后,您可以依赖已定义的默认客户转换器/映射器来执行映射。

CollectionMapperDecorator custom = new CollectionMapperDecorator(dozerMapper);
Collection<B> bees = custom.mapCollection(ayes, B.class);

public class CollectionMapperDecorator implements Mapper
{
   private Mapper baseMapper;

   public CollectionMapperDecorator(Mapper baseMapper)
   {
      this.baseMapper = baseMapper;      
   }

   public <T> Collection<T> mapCollection(Object[] source, Class<T> destinationClass)
   {
      return mapCollection(Arrays.asList(source), destinationClass);
   }

   public <T> Collection<T> mapCollection(Object[] source, Collection<T> destination, Class<T> destinationClass)
   {
      return mapCollection(Arrays.asList(source), destination, destinationClass);
   }

   public <T> Collection<T> mapCollection(Collection<? extends Object> source, Class<T> destinationClass)
   {      
      return mapCollection(source, null, destinationClass);
   }   

   public <T> Collection<T> mapCollection(Collection<? extends Object> source, Collection<T> destination, Class<T> destinationClass)
   {
      if(destination == null)
         destination = new ArrayList<T>();

      for(Object sourceObj : source)
      {
         destination.add(map(sourceObj, destinationClass));
      }

      return destination;      
   }

   public <T> T map(Object source, Class<T> destinationClass, String mapId) throws MappingException
   {
      return baseMapper.map(source, destinationClass, mapId);
   }

   public <T> T map(Object source, Class<T> destinationClass) throws MappingException
   {
      return baseMapper.map(source, destinationClass);
   }

   public void map(Object source, Object destination, String mapId) throws MappingException
   {
      baseMapper.map(source, destination, mapId);
   }

   public void map(Object source, Object destination) throws MappingException
   {
      baseMapper.map(source, destination);
   }
}