java - java modelMapper:将集合映射到对象
问题描述
经过对这个主题的大量测试和研究,我无法完全解决我的问题。我在 springboot 应用程序中使用 modelmapper 进行实体/DTO 映射。我正在尝试配置我的模型映射器以将 Set 映射到一个简单的 DTO 对象。我已经创建了一个自定义转换器,它按预期工作:
Converter<Set<CategoryTl>, CategoryTlDTO> converter = new AbstractCustomConverter<Set<CategoryTl>, CategoryTlDTO>() {
@Override
protected D convert(S source, MappingContext<Set<CategoryTl>, CategoryTlDTO> context) {
HashMap<String, CategoryTlDetailsDTO> map = new HashMap<>();
source.forEach(
categoryTl -> map.put(categoryTl.getCatalogLanguage().getLanguage().getCode(),
new CategoryTlDetailsDTO(categoryTl.getName(), categoryTl.getDescription()))
);
return new CategoryTlDTO(map);
}
};
我现在的问题是将此转换器应用于所有“Set => CategoryTlDTO”。是否在嵌套对象中。我尝试创建一个新的 TypeMap,但由于“Set”集合而无法创建。
mapper.createTypeMap(Set<CategoryTl>.class (-> not possible), CategoryTlDTO.class).setConverter(converter);
如果我直接在模型映射器中添加转换器,它就不起作用。
mapper.addConverter(converter);
您对此有任何提示或解决方案吗?也许我错过了关于 TypeToken 和 TypeMap Inheritance 的一些东西。
此致,
解决方案
我没有使用过 ModelMapper,但文档建议您可以使用 TypeToken
Type setType = new TypeToken<Set<CategoryTl>>() {}.getType();
mapper.createTypeMap(setType, CategoryTlDTO.class).setConverter(converter);
推荐阅读
- python - algorithm - 通过特定顶点的路径查找
- javascript - 如何在 django forms.DateInput 值中获取更新的当前日期
- python - 将 numpy 记录保存和加载为多部分文件
- c# - Unity - 使文本扩展然后收缩,就像向用户弹出一样。我想引起用户注意他们的分数
- c - 为什么char指针在签名后可以增值?
- python - Python youtube搜索如何获取“链接”?
- excel - 电子邮件显示但不发送
- ffmpeg - H264_Nvenc 的最佳设置以最小化延迟?(FFMPEG)
- javascript - 如何将上下文传递给 Javascript 承诺
- php - 如何使用 mysql 转换 json?