我有两个对象:
@Setter
@Getter
public class Agent {
public int userID;
public String name;
public boolean isVoiceRecorded;
public boolean isScreenRecorded;
public boolean isOnCall;
public LocalDateTime startEventDateTime;
}
public class AgentLine {
public int userID;
public String name;
public boolean isVoiceRecorded;
public boolean isScreenRecorded;
public boolean isOnCall;
public String startEventDateTime;
}我想在AgentLine到代理之间进行映射。由于Localdatetime转换,我不能使用默认映射。我已经定义了:
@Bean
ModelMapper getModelMapper() {
ModelMapper modelMapper = new ModelMapper();
Converter<AgentLine, Agent> orderConverter = new Converter<AgentLine, Agent>() {
@Override
public Agent convert(MappingContext<AgentLine, Agent> mappingContext) {
AgentLine s = mappingContext.getSource();
Agent d = mappingContext.getDestination();
/* d.userID = s.userID;
d.name = s.name;*/
d.startEventDateTime = LocalDateTime.parse(s.startEventDateTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
return d;
}
};
modelMapper.addConverter(orderConverter);
return modelMapper;
}为了使用它:
AgentLine line;
@Autowired
private ModelMapper modelMapper;
Agent agent = modelMapper.map(line, Agent.class);它可以工作,但我不想在convert方法中指定所有代理属性,我想指定startEventDateTime转换,其余属性将在默认情况下映射。
此外,我还试图定义:
PropertyMap<AgentLine, Agent> orderMap = new PropertyMap<AgentLine, Agent>() {
@Override
protected void configure() {
map().setName(source.name);
}
};
modelMapper.addMappings(orderMap);但是,在映射中,您不能处理日期转换。如果我为映射器PropertyMap和转换器定义,PropertyMap将被忽略。
我不想在convert方法中指定所有代理属性,我想指定startEventDateTime转换,其余属性将默认映射。
发布于 2018-01-04 16:53:21
不要使用Converter映射复杂对象。您应该使用TypeMap来实现这些目的。使用Converter进行自定义转换(对于从String到LocalDateTime的情况)。
ModelMapper modelMapper = new ModelMapper();
Converter<String, LocalDateTime> dateTimeConverter = ctx -> ctx.getSource() == null ? null : LocalDateTime.parse(ctx.getSource(), DateTimeFormatter.ISO_LOCAL_DATE_TIME);
modelMapper.typeMap(AgentLine.class, Agent.class)
.addMappings(mapper -> mapper.using(dateTimeConverter).map(AgentLine::getStartEventDateTime, Agent::setStartEventDateTime));https://stackoverflow.com/questions/48041483
复制相似问题