Java 如何使用modelMapper转换嵌套类
我有一个简单的类,我想使用modelMapper将其映射到DTO类Java 如何使用modelMapper转换嵌套类,java,modelmapper,Java,Modelmapper,我有一个简单的类,我想使用modelMapper将其映射到DTO类 class Source { private String name; private String address; List<Thing> things; // getters and setters follows } class Thing { private String thingCode; private String thingD
class Source {
private String name;
private String address;
List<Thing> things;
// getters and setters follows
}
class Thing {
private String thingCode;
private String thingDescription;
// getters and setters
}
但我不知道如何让映射器将事物列表转换为事物列表。从文档中,我认为我需要创建一个扩展PropertyMap的mapper类,但我无法确定如何配置它
任何指向相关文档的指针都是受欢迎的我认为,如果您将ModelMapper配置为松散或标准,它将为您提供帮助
modelMapper = new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE);
另外,您可以尝试下一步:
public class ListThingToThingDTOConverter implements Converter<List<Thing>, List<ThingDTO>> {
@Override
public List<ThingDTO> convert(MappingContext<List<Thing>, List<ThingDTO>> context) {
List<Thing> source = context.getSource();
List<ThingDTO> output = new ArrayList<>();
...
//Convert programmatically List<Thing> to List<ThingDTO>
...
return output;
}}
通过创建泛型,可以像下面的代码一样映射。参考链接 进口:
import java.lang.reflect.Type;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
在服务或控制器类中:
ModelMapper modelMapper = new ModelMapper();
Type listType = new TypeToken<SourceDTO>(){}.getType();
SourceDTO sourceDTO = modelMapper.map(source,listType);
ModelMapper ModelMapper=newmodelmapper();
类型listType=newTypeToken(){}.getType();
SourceDTO SourceDTO=modelMapper.map(source,listType);
public class SourceToSourceDTOMap extends PropertyMap<Thing, ThingDTO> {
@Override
protected void configure(){
using(new ListThingToThingDTOConverter()).map(source.getThings()).setThings(null);
}
modelMapper = new ModelMapper();
modelMapper.addMappings(new SourceToSourceDTOMap());
import java.lang.reflect.Type;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
ModelMapper modelMapper = new ModelMapper();
Type listType = new TypeToken<SourceDTO>(){}.getType();
SourceDTO sourceDTO = modelMapper.map(source,listType);