java ModelMapper转换器不工作
我在rest应用程序中使用ModelMapper
我必须把列表转换成列表
这是我的代码:
Converter<List<UserRole>,List<String>> listConverter = new Converter<List<UserRole>, List<String>>() {
public List<String> convert(MappingContext<List<UserRole>, List<String>> context) {
List<String> target = new ArrayList<String>();
List<UserRole> userRoles = context.getSource();
for (UserRole userRole : userRoles) {
target.add(userRole.getRole().getName());
}
return target;
}
};
PropertyMap<User, UserDTO> propertiesForConvertToDto = new PropertyMap<User, UserDTO>() {
protected void configure() {
using(listConverter).map(source.getUserRoles()).setRoles(null);
}
};
当我运行应用程序时,会出现以下错误:
HTTP Status 500 - Request processing failed; nested exception is org.modelmapper.MappingException: ModelMapper mapping errors:
type Exception report
message Request processing failed; nested exception is org.modelmapper.MappingException: ModelMapper mapping errors:
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.modelmapper.MappingException: ModelMapper mapping errors:
1) Failed to instantiate instance of destination java.util.List. Ensure that java.util.List has a non-private no-argument constructor.
Caused by: java.lang.NoSuchMethodException: java.util.List.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.getDeclaredConstructor(Class.java:2178)
at org.modelmapper.internal.MappingEngineImpl.instantiate(MappingEngineImpl.java:366)
at org.modelmapper.internal.MappingEngineImpl.createDestination(MappingEngineImpl.java:382)
你能帮我吗?我花了五个小时试图解决这个问题。调试时,我知道转换器工作正常。我打错电话了吗
# 1 楼答案
在映射之前,请使用下面的代码片段实现ModelMapper
现在尝试映射对象值,如
别忘了添加jar文件 https://mvnrepository.com/artifact/org.modelmapper/modelmapper/0.7.5