首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ModelMapper未映射

ModelMapper未映射
EN

Stack Overflow用户
提问于 2018-12-13 07:45:17
回答 1查看 3.6K关注 0票数 1

当我尝试通过Enum将源中的字符串映射到目标中的Integer。ModelMapper失败。

来源

代码语言:javascript
复制
public class Request {
    private String classification;
}

目的地

代码语言:javascript
复制
public class DTO {
    private Integer classification;
}

字符串和整数之间的映射在ENUM中定义

代码语言:javascript
复制
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;
}
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-13 19:45:10

您需要在那里使用Converter

代码语言:javascript
复制
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));
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53753075

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档