Java object mapper is a library that you can use to convert a Java class to another class in a seamless way. This library also supports converting a list of objects instead of a single object. This library is built by GSON v2.9.0
.
Add this repository to your pom.xml
<repositories>
<repository>
<id>repo-contoh-gratis</id>
<name>repo-contoh-gratis</name>
<url><http://repo.contoh.gratis:81/repository/maven-public/></url>
</repository>
</repositories>
Add this dependency to your pom.xml
<dependency>
<groupId>gratis.contoh</groupId>
<artifactId>mapper</artifactId>
<version>1.0.0</version>
</dependency>
Run mvn clean install
Simple java class
public class App {
public static void main(String[] args) {
ObjectMapper<ModelA, ModelB> mapper = new MapperTemplate<>(
ModelA.class,
ModelB.class,
new FieldMapper("field1From", "field1To"),
new FieldMapper("field2From", "field2To"));
ModelA modelA = new Model();
ModelB modelB = mapper.convert(model);
}
}
class ModelA {
// ...properties
}
class ModelB {
// ...properties
}
Springboot
Create a configuration class
@Configuration
public class AutoMapperConfiguration {
@Bean
ObjectMapper<ModelA, ModelB> modelAModelBMapper() {
return new MapperTemplate<>(
ModelA.class,
ModelB.class,
new FieldMapper("field1From", "field1To"),
new FieldMapper("field2From", "field2To"));
}
}
Use the mapper
@RestController
@RequestMapping("/mapper")
public class MapperSampleController {
@Autowired
private ObjectMapper<ModelA, ModelB> mapper;
@PostMapping("")
public ResponseEntity<ModelB> mapperTest(@RequestBody @Valid ModelA model) {
return ResponseEntity.ok(mapper.convert(model));
}
}
You can pass an object or list of objects to convert
method. This convert
method also could receive FieldNamingPolicy
from the GSON
library if you need to change it.
You can see the code in this GitHub link. Feel free to fork, edit, or any action you need related to the code.