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.

Prerequisite

How to Import the Library

  1. 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>
    
  2. Add this dependency to your pom.xml

    <dependency>
    	<groupId>gratis.contoh</groupId>
    	<artifactId>mapper</artifactId>
    	<version>1.0.0</version>
    </dependency>
    
  3. Run mvn clean install

How to Use the Library

  1. 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
    }
    
  2. Springboot

    1. 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"));
          }
          
      }
      
    2. 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.

Source Code

You can see the code in this GitHub link. Feel free to fork, edit, or any action you need related to the code.