Horje
Generate Model Classes using jsonSchema2Pojo (website and Maven Dependency) For a Spring Boot Project That Consumes API

Generating Java model classes from a JSON schema is a common task when building applications that consume APIs, especially in Spring Boot projects. It simplifies the development process by mapping POJOs (Plain Old Java Objects) directly to the API’s JSON structure. In this article, we explore how to use jsonSchema2Pojo, both as a web tool and as a Maven dependency in a Spring Boot project.

jsonSchema2Pojo A tool that generates Java types from JSON or JSON Schema. It can be installed in a build through its web browser or Maven or Gradle for faster generation.

Using the jsonSchema2Pojo Website

1. Prepare the JSON Schema: Make sure you have the JSON schema for the API response. It is the simple example of the JSON schema:

{
"type": "object",
"properties": {
"id": {"type": "integer"},
"name": {"type": "string"},
"email": {"type": "string"},
"isActive": {"type": "boolean"}
},
"required": ["id", "name"]
}

2. Generate the Classes: Visits the jsonSchema2Pojo.

  • Paste the schema into the input area.
  • Configure the options like package, Source Type and their output format.
  • Then click the preview or Download to see the generated the Java code.

Using the jsonSchema2Pojo Maven Plugin

1. Add the Plugin to pom.xml:

<plugin>
<groupId>org.jsonschema2pojo</groupId>
<artifactId>jsonschema2pojo-maven-plugin</artifactId>
<version>1.1.1</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<sourceDirectory>${project.basedir}/src/main/resources/schema</sourceDirectory>
<outputDirectory>${project.basedir}/src/main/java</outputDirectory>
<targetPackage>com.example.models</targetPackage>
<usePrimitives>true</usePrimitives>
</configuration>
</execution>
</executions>
</plugin>

2. Prepare the Schema File: We can save the JSON schema in the src/main/resources/schema.

3. Run the Maven Command: Execute the Maven goal to generate the Java classes:

mvn jsonschema2pojo:generate

4. Verify the Generated Classes: Check the specified package for the generated the Java classes.

Implementation to Generate Model Classes using jsonSchema2Pojo for a Spring Boot Project which Consumes API

Below are the implementation steps to Generate Model Classes using jsonSchema2Pojo for a Spring Boot Project which Consumes API.

Step 1:

Create a Spring Boot project using the Spring Initializr and add dependencies:

Dependencies:

  • Spring Web
  • Lombok
  • Spring Devtools

External dependencies:

        <dependency>
<groupId>org.jsonschema2pojo</groupId>
<artifactId>jsonschema2pojo-maven-plugin</artifactId>
<version>1.2.1</version>
</dependency>

Maven Plugin configuration:

<plugin>
<groupId>org.jsonschema2pojo</groupId>
<artifactId>jsonschema2pojo-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<sourceDirectory>${project.basedir}/src/main/resources/schema</sourceDirectory>
<targetPackage>com.example.models</targetPackage>
<generateBuilders>true</generateBuilders>
<usePrimitives>false</usePrimitives>
<annotationStyle>jackon</annotationStyle>
<sourceType>jsonschema</sourceType>
</configuration>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
<phase>generate-sources</phase>
</execution>
</executions>
</plugin>


After creating the project, the file structure will look like below.

File Structure


Step 2:

Open the application.properties file and put the below code for the server port configuration to the project.

spring.application.name=spring-jsonschema2pojo-schema
server.port=8080


Step 3: Create POJO Class

Create the new package and name it as “model”. Inside that package, create a new Java class named “GeneratedModel”. Go to org.example.springjsonschema2pojoschema > model > GeneratedModel and put the below code.

Java
package org.example.springjsonschema2pojoschema.model;


import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class GeneratedModel {
    @JsonProperty("id")
    private Integer id;

    @JsonProperty("name")
    private String name;

    // Getters and setters
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


Step 4: Create Service Class

Create a new package named “service”. Inside that package, create a new Java class named “APIService”. Go to org.example.springjsonschema2pojoschema > service > APIService and put the below code.

Java
package org.example.springjsonschema2pojoschema.service;

import org.example.springjsonschema2pojoschema.model.GeneratedModel;
import org.springframework.stereotype.Service;

@Service
public class ApiService {

    public GeneratedModel getData() {
        // Assume this data might be retrieved through an API call
        GeneratedModel model = new GeneratedModel();
        model.setId(1);
        model.setName("Example Name");
        return model;
    }
}


Step 5: Create Controller Class

Create a new package named “controller”. Inside that package, create a new Java class named “MyController”. Go to org.example.springjsonschema2pojoschema > controller > MyController and put the below code.

Java
package org.example.springjsonschema2pojoschema.controller;

import org.example.springjsonschema2pojoschema.model.GeneratedModel;
import org.example.springjsonschema2pojoschema.service.ApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @Autowired
    private ApiService apiService;

    @GetMapping("/data")
    public GeneratedModel getData() {
        return apiService.getData();
    }
}


Step 6: Main Class

Open the main class and put the below code(No changes are required).

Java
package org.example.springjsonschema2pojoschema;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringJsonschema2pojoSchemaApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringJsonschema2pojoSchemaApplication.class, args);
    }

}


Output:

JSON Generate:

mvn jsonschema2pojo:generate

Console Output:

JSON Generate Output


JSON schema will be generated in src/main/resources/schema of the project.

{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Person",
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string"
}
},
"required": ["id", "name"]
}


Step 7: Run the Application

Once the Spring project is completed and run as a Spring application successfully, it will start at port 8080.

Application Runs


Data endpoint Testing:

GET http://localhost:8080/data

Output:

API Testing





Reffered: https://www.geeksforgeeks.org


Advance Java

Related
Difference between JPA and Spring Data JPA Difference between JPA and Spring Data JPA
Configuring a Hikari Connection Pool with Spring Boot Configuring a Hikari Connection Pool with Spring Boot
Advanced Java Tutorial | Mastery in Java Programming Advanced Java Tutorial | Mastery in Java Programming
Top 30+ Java Microservices Interview Questions and Answers (2024) Top 30+ Java Microservices Interview Questions and Answers (2024)
Getting Started with Spring Boot and Eureka Service Registry Getting Started with Spring Boot and Eureka Service Registry

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
15