2011-08-26 114 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); 
相關問題