JsonSchema to POJO Objects in Java / Maven

Converting the json or jsonschema to Pojo objects in java would be the regular tasks when we are working with multiple teams or systems or interfaces where as the json is the primary file type used for transfering the informations.

So going forward every microservices based projects must require this utility code to generate the json schema to java pojo objects.

In your existing maven project,

1. Add this dependency:

<dependency>
	<groupId>org.jsonschema2pojo</groupId>
	<artifactId>jsonschema2pojo-core</artifactId>
	<version>1.0.2</version>
</dependency>

2. Keep your json schema in src/main/resources/schema

3. Json Schema to Pojo Generation Code snippet

Change your folder structure in the below snippet if its different than what mentioned in step 2 above.

URL source = JsonSchemaGeneration.class.getResource("/schema/myntra-products.json");

Change your Main Response Class name & the package structure however you want in the below snippets,

mapper.generate(codeModel, "MyntraProductsResponse", "com.ngdeveloper.products", source);

JsonSchemaGeneration:

package com.ngdeveloper.jsonschema2pojo;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;

import org.jsonschema2pojo.DefaultGenerationConfig;
import org.jsonschema2pojo.GenerationConfig;
import org.jsonschema2pojo.Jackson2Annotator;
import org.jsonschema2pojo.SchemaGenerator;
import org.jsonschema2pojo.SchemaMapper;
import org.jsonschema2pojo.SchemaStore;
import org.jsonschema2pojo.SourceType;
import org.jsonschema2pojo.rules.RuleFactory;

import com.sun.codemodel.JCodeModel;

public class JsonSchemaGeneration {

  public static void main(String[] args) throws IOException {
    JCodeModel codeModel = new JCodeModel();
    URL source = JsonSchemaGeneration.class.getResource("/schema/myntra-products.json");
    GenerationConfig config = new DefaultGenerationConfig() {
      @Override
      public boolean isGenerateBuilders() { // set config option by overriding method
        return true;
      }

      @Override
      public SourceType getSourceType() {
        return SourceType.JSON;
      }
    };

    SchemaMapper mapper = new SchemaMapper(
      new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());
    mapper.generate(codeModel, "MyntraProductsResponse", "com.ngdeveloper.products", source);

    File file = Files.createTempDirectory("required").toFile();
    codeModel.build(file);
    System.out.println("path is " + file);
  }
}

4. Generated Pojo Files

5. Download

Leave a Reply