2011-08-26 60 views
18

此问题与AutoMapper无关。 我的问题是关于java中的ModelMapper,但是我不能为modelmapper创建新的标签,因为我的小声望。抱歉混淆。ModelMapper库是否支持像ArrayList或HashSet这样的集合?

无论如何,我的问题是图书馆是否支持象arraylist或hashset的集合?它似乎不支持收集到集合映射。 这是真的吗?

回答

2

是 - 支持Collection to Collection映射。例如:

static class SList { 
    List<Integer> name; 
} 

static class DList { 
    List<String> name; 
} 

public void shouldMapListToListOfDifferentTypes() { 
    SList list = new SList(); 
    list.name = Arrays.asList(Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3)); 
    DList d = modelMapper.map(list, DList.class); 

    assertEquals(d.name, Arrays.asList("1", "2", "3")); 
} 
+0

在这个例子中,你使用周围的集合两个包装类。没有他们会有可能吗? – miguelcobain

+0

@miguelcobain - 是的,包装恰好是我给的例子。 – Jonathan

29

您也可以直接映射集合():

List<Person> persons = getPersons(); 
    // Define the target type 
    java.lang.reflect.Type targetListType = new TypeToken<List<PersonDTO>>() {}.getType(); 
    List<PersonDTO> personDTOs = mapper.map(persons, targetListType); 

Documentation on mapping Generics

3

您也可避免TypeToken的东西,如果你使用数组:

List<PropertyDefinition<?>> list = ngbaFactory.convertStandardDefinitions(props); 
    ModelMapper modelMapper = new ModelMapper(); 
    PropertyDefinitionDto[] asArray = modelMapper.map(list, PropertyDefinitionDto[].class); 
相关问题