I have two objects that have two separate representations of a string and I am using Dozer to perform object-to-object mapping. I am having a problem running bi-directional data conversion when a string on one object is mapped to a string on another using a custom converter.
Say for example you have:
public class ClassA { private string1; }
and
public class ClassB { private string1; }
The data conversion is setup as follows:
ClassA String ClassB String --------------- --------------- STRING_A_1 <-> STRING_A_2 STRING_B_1 <-> STRING_B_2 STRING_C_xxx <-> STRING_C_xxx
My mapper is set up as follows:
public class CustomConverter extends DozerConverter<String, String> implements MapperAware {
public CustomConverter() {
super(String.class, String.class);
}
@Override
public String convertTo(String source, String target) {
return MyEnum.toA(source);
}
@Override
public String convertFrom(String source, String target) {
return MyEnum.toB(source);
}
}
The only method that gets called is convertFrom(String, String)
. I tried implementing the MapperAware
interface but did not see any means of loading the source and target class types. I was hoping to detect in either method what is being called to figure out the appropriate mapping direction to use.
How can I use my converter to detect what the actual direction of the mapping should be?
In a Dozer converter, convertFrom and convertTo are called solely based on their parameter type. The order of class-a and class-b in the mapping configuration are not considered.
Thus as you noted, only convertFrom is called.
The issue here is that Dozer is doing class instance conversion, while you really require string conversion.
Thus you will need to identify the format of the source string and do the conversion manually.
Alternatively, if you can use JSON, then a JSON parsing library will do this for you. E.g. in Jackson:
jsonMapper = new ObjectMapper();
A a = jsonMapper.readValue(new StringReader(source), A.class);
B b = dozerMapper.map(a, B.class);
StringWriter sw = new StringWriter();
jsonMapper.writeValue(sw, b);
target = sw.toString();