当我尝试通过Enum将源中的字符串映射到目标中的Integer。ModelMapper失败。
来源
public class Request {
private String classification;
}目的地
public class DTO {
private Integer classification;
}字符串和整数之间的映射在ENUM中定义
public enum Classification {
POWER(3, "Power"),
PERFORMANCE(4, "Performance"),
TASK(13, "Task");
private final Integer code;
private final String name;
ProblemClassification(final int code, final String name) {
this.code = code;
this.name = name;
}
public Integer getCode() {
return code;
}
public String getName() {
return name;
}
public static Integer getCodeByName(String name) {
Optional<Classification> classification = Arrays.asList(Classification.values()).stream()
.filter(item -> item.getName().equalsIgnoreCase(name))
.findFirst();
return classification.isPresent() ? classification.get().getCode() : null;
}
}发布于 2018-12-13 19:45:10
您需要在那里使用Converter:
ModelMapper modelMapper = new ModelMapper();
Converter<String, Integer> classificationConverter =
ctx -> ctx.getSource() == null ? null : Classification.getCodeByName(ctx.getSource());
modelMapper.typeMap(Request.class, DTO.class)
.addMappings(mapper -> mapper.using(classificationConverter).map(Request::getClassification, DTO::setClassification));https://stackoverflow.com/questions/53753075
复制相似问题