I want to map a SourceClass
type to a DestinationClass
type.
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;
}
Currently I using a custom Converter
to do the mapping, to convert String
to 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());
}
And use 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);
So, the source object and destination object should be:
// 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"
}
}
I have read this question before => How to customize ModelMapper
The solution note the ModelMapper
custom mappings are added to the default mappings, so you do not need, for example, to specify id
:
// you don't need to write this statement.
map(source.getId()).setId(null);
So I am thinking about, is there anyway to change (or override) the default mappings, so that I can write less code.
Maybe it looks like:
ModelMapper modelMapper = new ModelMapper();
// ...
// something will change default mappings to myConverter
// ...
modelMapper.map(source, DestinationClass.class);
Thank you for all Helps and Answers.