Java 将项目列表转换为单个对象

Java 将项目列表转换为单个对象,java,mapping,modelmapper,Java,Mapping,Modelmapper,我需要将项目列表转换为单个dto项目。如果列表中有任何元素,我们将使用第一个元素。 我用这种方式实现了转换器接口,但它不起作用。转换后,目标项为空 public class LocationConverter implements Converter<List<Location>,LocationDto> { @Override public LocationDto convert(MappingContext<List<Location>, Loca

我需要将项目列表转换为单个dto项目。如果列表中有任何元素,我们将使用第一个元素。 我用这种方式实现了转换器接口,但它不起作用。转换后,目标项为空

public class LocationConverter implements Converter<List<Location>,LocationDto> {

@Override
public LocationDto convert(MappingContext<List<Location>, LocationDto> mappingContext) {
    ModelMapper modelMapper = new ModelMapper();
    List<Location> locations = mappingContext.getSource();
    LocationDto locationDto = mappingContext.getDestination();
    if (locations.size() >= 1) {
        Location location = locations.get(0);
        modelMapper.map(location, locationDto);
        return locationDto;
    }
    return null;
   }
}

 ModelMapper modelMapper = new ModelMapper();
 modelMapper.addConverter(new LocationConverter());
 Event event = new Event();
 modelMapper.map(event, eventDto);
公共类LocationConverter实现转换器{
@凌驾
要转换的公共位置(MappingContext MappingContext){
ModelMapper ModelMapper=新的ModelMapper();
List locations=mappingContext.getSource();
LocationDto LocationDto=mappingContext.getDestination();
如果(locations.size()>=1){
位置=位置。获取(0);
modelMapper.map(位置,locationDto);
返回位置DTO;
}
返回null;
}
}
ModelMapper ModelMapper=新的ModelMapper();
addConverter(新的LocationConverter());
事件=新事件();
map(event,eventDto);
我应用此转换器的实体看起来是这样的:

public class Event extends BasicEntity  {

  private Integer typeId;

  private String typeName;

  private List<Location> locationList;

}


public class EventDto {

    private Integer typeId;

   private String typeName;

   private LocationDto location;
}
公共类事件扩展基本度{
私有整数类型ID;
私有字符串类型名;
私有列表位置列表;
}
公共类事件{
私有整数类型ID;
私有字符串类型名;
私人场所到场所;
}

因此,我需要将Event中的位置列表转换为EventDto中的LocationDto。

我们可以为每个属性映射定义一个转换器,这意味着我们可以使用自定义转换器将locationList映射到位置

使用Java8

modelMapper.typeMap(Event.class, EventDto.class).addMappings(
        mapper -> mapper.using(new LocationConverter()).map(Event::getLocationList, EventDto::setLocation));
使用Java 6/7

modelMapper.addMappings(new PropertyMap() {
    @Override
    protected void configure() {
        using(new LocationConverter()).map().setLocation(source.getLocationList());
    }
});

“它不起作用。”你知道为什么我们在理解细节时会有困难吗?让你知道:你的列表是一个单一的对象,你说“它不工作”是什么意思?@daniu,我为不准确道歉。我编辑了这个问题,希望它现在更清楚。您的呼叫不应该是
modelMapper.map(event,eventDto)
?@daniu,是的,应该是,只是一个输入错误。我从另一个方法复制了代码。