I have a few DTOs (from different APIs) that I need to convert. They have similar, but different fields.
Example:
class Volkswagen {
String model;
int year;
String colour;
}
class BMW {
String make;
int manufactureYear;
String colour;
}
What is the best way to convert these DTOs to my standard DTO?
I know there is BeanUtils, but there is not a direct way to map the fields. Currently, I am extracting one set of properties as VolkswagenMap, changing its keys using another V2BMap, and finally populating my standard DTO using a third BMWMap. As in,
extract()
{"model": "Beetle", "year": 1990}
-> {"model": "make", "year": "manufacturedYear"}
-> {"make": "Beetle", "manufacturedYear": 1990}
populate()
Is there a more elegant way to do it? Thx in advance.
It's probably best to have a common interface for both. Then all of your service methods could act upon the interface instead of the concrete types.
If you can change the sources of
VolkswagenandBMWyou could have both implement a common interface.If you can't change the sources of
VolkswagenandBMWyou could create adapters for each that implement a common interface.Eg