Wednesday, 31 March 2021

Generate POJOs from json schema

 Follow below step-by-step procedure to generate model classes.

 

Step 1: Define an instance of Jackson2Annotator. Jackson2Annotator class generates Java types using the Jackson 2.x mapping annotations.

GenerationConfig generationConfig = new DefaultGenerationConfig() {
    @Override
    public boolean isGenerateBuilders() {
        return true;
    }

    public SourceType getSourceType() {
        return SourceType.JSONSCHEMA;
    }
};

Jackson2Annotator jackson2Annotator = new Jackson2Annotator(generationConfig);

 

Step 2: Define SchemaMapper instance. SchemaMapper generates Java types from a JSON schema. Can accept a factory which will be used to create type generation rules for this mapper.

SchemaStore schemaStore = new SchemaStore();
RuleFactory ruleFactory = new RuleFactory(generationConfig, jackson2Annotator, schemaStore);
SchemaMapper mapper = new SchemaMapper(ruleFactory, new SchemaGenerator());

Step 3: Reads schema and adds generated types to the given code model.

JCodeModel jCodeModel = new JCodeModel();

File inputJson = new File(INPUT_JSON_FILE);
URL inputJsonURL = inputJson.toURI().toURL();

mapper.generate(jCodeModel, "Employee", PACKAGE_NAME, inputJsonURL);


If the input file is located in classpath, you can get the file url using below statement.

URL inputJsonURL = PojoFromJsonDocument.class.getClassLoader().getResource(INPUT_JSON_FILE);


Step 4: Write the generated types to the output directory.

File outputPojoDirectory = new File(OUTPUT_DIR);
outputPojoDirectory.mkdirs();
jCodeModel.build(outputPojoDirectory);


Find the below working application.

 

addressSchema.json

{
    "$id": "https://example.com/address.schema.json",
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "description": "An address similar to http://microformats.org/wiki/h-card",
    "type": "object",
    "properties": {
        "post-office-box": {
            "type": "string"
        },
        "extended-address": {
            "type": "string"
        },
        "street-address": {
            "type": "string"
        },
        "locality": {
            "type": "string"
        },
        "region": {
            "type": "string"
        },
        "postal-code": {
            "type": "string"
        },
        "country-name": {
            "type": "string"
        }
    },
    "required": [
        "locality",
        "region",
        "country-name"
    ],
    "dependentRequired": {
        "post-office-box": [
            "street-address"
        ],
        "extended-address": [
            "street-address"
        ]
    }
}


PojoFromJsonSchema.java

import java.io.File;
import java.io.IOException;
import java.net.URL;

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 PojoFromJsonSchema {
    private static final String INPUT_JSON_FILE = "addressSchema.json";
    private static final String PACKAGE_NAME = "com.sample.app.model";
    private static final String OUTPUT_DIR = "/Users/Shared/json/modelClasses";

    public static void main(String[] args) throws IOException {

        GenerationConfig generationConfig = new DefaultGenerationConfig() {
            @Override
            public boolean isGenerateBuilders() {
                return true;
            }

            public SourceType getSourceType() {
                return SourceType.JSONSCHEMA;
            }
        };

        Jackson2Annotator jackson2Annotator = new Jackson2Annotator(generationConfig);

        SchemaStore schemaStore = new SchemaStore();
        RuleFactory ruleFactory = new RuleFactory(generationConfig, jackson2Annotator, schemaStore);
        SchemaMapper mapper = new SchemaMapper(ruleFactory, new SchemaGenerator());

        JCodeModel jCodeModel = new JCodeModel();

        URL inputJsonURL = PojoFromJsonDocument.class.getClassLoader().getResource(INPUT_JSON_FILE);

        mapper.generate(jCodeModel, null, PACKAGE_NAME, inputJsonURL);

        File outputPojoDirectory = new File(OUTPUT_DIR);
        outputPojoDirectory.mkdirs();
        jCodeModel.build(outputPojoDirectory);
    }
}


Run the application ‘PojoFromJsonSchema’, you will see following message in console.

com/sample/app/model/AddressSchema.java

 

Open the file AddressSchema.java to see the content of the file.








 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment