gpt4 book ai didi

enums - ModelMapper 不映射

转载 作者:行者123 更新时间:2023-12-02 20:10:17 27 4
gpt4 key购买 nike

当我尝试通过枚举将源中的字符串映射到目标中的整数时。 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;
}
}

最佳答案

您需要转换器:

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

关于enums - ModelMapper 不映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53753075/

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