gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:08:16 25 4
gpt4 key购买 nike

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

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);

我应用此转换器的实体看起来是这样的:

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;
}

所以我需要将 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());
}
});

关于java - 将项目列表转换为单个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50871553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com