我有一个服务,它会返回List
个A
个对象。
我想将其转换为List
,例如B
个对象。
我已经定义了从A
到B
的映射。
天真,我试着做
List<A> ayes = ... // call to service
List<B> bees = dozerMapper.map(ayes, new ArrayList<B>().getClass());
但是,bees
仍是List
个A
个对象。
我该怎么办?
答案 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);
}
}