During one of mobile application development, we reused the services written for the web by exposing them as REST services for mobile. In which, we simply converted the “Object Model” used for web as JSON response for mobile. The “Object Model” which we used for the web is a bit heavier and all the object properties are not required for mobile. Here, we found some of the disadvantages with heavier data transfer to the mobile client. Some of the issues are “High bandwidth consumption to transfer the huge data over the network”, “Lot of space consumption on mobile which will ultimately hit the performance (Some times, if the app consumes more memory, during the review of the app, the respective app stores will reject the app)”. To make the “Object Model” lighter to suite to the thin clients, we wrote some converters which will copy the required properties from POJOs to the “Object Model” used for mobile. Later, we found there is a “Model Mapper” framework to do this job in a clean manner.
Follow the below steps to use ModelMapper.
- Create a maven project.
- Add the below dependency to pom.xml
org.modelmapper modelmapper 0.6.2
- Create ModelMapper object.
ModelMapper modelMapper = new ModelMapper();
- Pass the source object and the destination class to the ModelMapper’s map method.
In the above code, ModelMapper will analyze source and destination object properties to determine which properties implicitly match according to a matching strategy.
If you have some complex structure of objects, then you can use an explicit mapping strategy provided by ModelMapper.
You can find more details here.
The source code used in this article is available here.