Automate POJO Generation in Spring Boot 3 with jsonschema2pojo

This guide shows how to eliminate manual POJO coding in Spring Boot 3 by using jsonschema2pojo to generate Java classes directly from JSON Schema or raw JSON, covering Maven dependencies, configuration, code examples, and plugin setup.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Automate POJO Generation in Spring Boot 3 with jsonschema2pojo

1. Introduction

In backend development, writing POJO classes that mirror JSON structures is repetitive and error‑prone. Developers must define each field and match data types, which consumes time and often leads to bugs during API integration.

2. What is jsonschema2pojo?

jsonschema2pojo is a library that automatically converts JSON Schema or raw JSON data into Java POJOs that follow standard conventions, removing the need for manual coding and reducing the risk of omissions or type mismatches.

3. What is JSON Schema?

JSON Schema is a specification for describing and validating the structure of JSON data. It defines field names, data types, constraints, and required properties, enabling reliable data exchange and interface standardisation.

2.1 Prepare the Environment

Add the following Maven dependencies to your Spring Boot 3.5.0 project:

<dependency>
  <groupId>org.jsonschema2pojo</groupId>
  <artifactId>jsonschema2pojo-core</artifactId>
  <version>1.3.3</version>
</dependency>
<dependency>
  <groupId>org.glassfish.jaxb</groupId>
  <artifactId>codemodel</artifactId>
  <version>4.0.6</version>
</dependency>
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.20.0</version>
</dependency>

2.2 Generate Java Classes from a JSON Schema

Define a JSON Schema for a Product object:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "http://pack.com/product.schema.json",
  "title": "Product",
  "description": "商品信息",
  "type": "object",
  "properties": {
    "productId": {"description": "唯一标识", "type": "integer"},
    "productName": {"description": "商品名称", "type": "string"},
    "price": {"description": "商品价格", "type": "number", "exclusiveMinimum": 0},
    "tags": {"description": "商品标签", "type": "array", "items": {"type": "string"}, "minItems": 1, "uniqueItems": true}
  },
  "required": ["productId", "productName", "price"]
}

Use the following Java code to generate the POJO:

String schema = """
    ...
    """;
JCodeModel codeModel = new JCodeModel();
GenerationConfig config = new DefaultGenerationConfig() {
    @Override public boolean isGenerateBuilders() { return true; }
    @Override public boolean isIncludeAdditionalProperties() { return false; }
    @Override public boolean isIncludeGeneratedAnnotation() { return false; }
    @Override public boolean isUseLongIntegers() { return true; }
    @Override public boolean isUseBigDecimals() { return true; }
};
SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());
mapper.generate(codeModel, "Product", "com.pack", schema);
codeModel.build(new File("F://genclass"));

The generated class includes builder methods, proper type handling, and optional annotations. Note that the default @Generated annotation may contain an incorrect package name that must be corrected manually.

2.3 Generate Java Classes Directly from JSON Data

Define a JSON document representing a book:

{
  "name": "Spring Boot 3实战案例锦集",
  "price": 70,
  "author": "Pack_xg",
  "tags": ["Java", "Spring", "Spring Boot", "Spring Cloud"],
  "Profile": {"city": "乌鲁木齐", "country": "中国"}
}

Generate the corresponding POJOs with this code (notice the SourceType.JSON override):

String json = """
    ...
    """;
JCodeModel jcodeModel = new JCodeModel();
GenerationConfig config = new DefaultGenerationConfig() {
    @Override public boolean isGenerateBuilders() { 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(jcodeModel, "Book", "com.pack", json);
jcodeModel.build(outputJavaClassDirectory);

The process creates two classes: Book and Profile, as shown in the screenshots below.

2.4 Automate Generation with the Maven Plugin

Add the following plugin configuration to your pom.xml to generate POJOs during the build:

<plugin>
  <groupId>org.jsonschema2pojo</groupId>
  <artifactId>jsonschema2pojo-maven-plugin</artifactId>
  <version>1.3.3</version>
  <configuration>
    <sourceDirectory>${basedir}/src/main/resources/schema</sourceDirectory>
    <targetPackage>com.pack.json_gen_class</targetPackage>
  </configuration>
  <executions>
    <execution>
      <goals>
        <goal>generate</goal>
      </goals>
    </execution>
  </executions>
</plugin>

The schema files placed under src/main/resources/schema are processed, and the generated classes appear as illustrated in the following screenshots.

3. Important Note

The generated classes contain a @Generated annotation whose package name may be incorrect; you need to edit it manually.

For a complete list of supported options, visit the official site: https://www.jsonschema2pojo.org/
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JSON SchemaSpring BootMaven Pluginjsonschema2pojoPOJO generation
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.