【问题标题】:How to map List<A> to List<B> with Dozer?如何使用 Dozer 将 List<A> 映射到 List<B>?
【发布时间】:2014-10-10 14:41:46
【问题描述】:

我有一个服务,它返回一个List,比如A 对象。 我想将其转换为 ListB 对象。

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

天真地,我试着去做

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

但是,bees 仍然是 ListA 对象。

我该怎么办?

【问题讨论】:

    标签: list map dozer


    【解决方案1】:

    我认为您可以在 Dozer 中使用提示 http://dozer.sourceforge.net/documentation/collectionandarraymapping.html 实现此目的,但我们发现围绕默认 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);
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-19
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 2019-10-23
      • 1970-01-01
      • 2018-06-29
      相关资源
      最近更新 更多