有没有办法更改默认映射?

时间:2019-04-15 07:03:07

标签: java modelmapper

我想将args类型映射到args.object类型。

SourceClass
DestinationClass

当前,我使用自定义public class SourceClass { private Integer id; private String number; private String username; private String email; } 进行映射,将public class DestinationClass { private Integer id; private Map<String, Object> number; private Map<String, Object> username; private Map<String, Object> email; } 转换为Converter

String

并使用Map<String, Object>

// this function will new and set a map object
public Map<String, Object> setData(String title, Object value {
    Map<String, Object> result = Maps.newHashMap();
    result.put("title", title);
    result.put("value", value);

    return result;
}

// this function will return my custom converter
public Converter<String, Map<String, Object>> myConverter(String title) {
    // LocalI18nUtils.getString(String key) input key and get the translation
    return ctx -> setData(LocalI18nUtils.getString(title), ctx.getSource());
}

因此,源对象和目标对象应为:

modelMapper.addMappings()
PropertyMap<SourceClass, DestinationClass> mappings = new PropertyMap<SourceClass, DestinationClass>() {
    @Override
    protected void configure() { 
using(myConverter("Number"))).map(source.getNumber()).setNumber(null);
using(myConverter("Username"))).map(source.getUsername()).setUsername(null);
using(myConverter("Email"))).map(source.getEmail()).setEmail(null);
    }
}

// source is SourceClass type object
ModelMapper modelMapper = new ModelMapper();
modelMapper.addMappings(mappings);
modelMapper.map(source, DestinationClass.class);

我已经在=> How to customize ModelMapper

之前阅读过此问题

解决方案说明// source { "id": 1, "number": "mem_0001", "username": "member0001", "email": "member001@mail.com" } 自定义映射已添加到默认映射,因此,例如,您无需指定// destination { "id": 1, "number": { "title": "Number", "value": "mem_0001" }, "username": { "title": "Username", "value": "member0001" }, "email": { "title": "Email", "value": "member001@mail.com" } }

ModelMapper

所以我正在考虑,是否有必要更改(或覆盖)默认映射,以便减少编写代码。

也许看起来像:

id

感谢您的所有帮助和解答。

0 个答案:

没有答案