Example JSON as Parameter

As mentioned above, we will create one sample spring boot app with a POST endpoint. Which takes the Person JSON file as input.

We can create a spring boot application by using the below-

  1. Spring initializer (spring.io)
  2. Using IDE (Eclipse / STS)
  3. Spring Cli console and so on.

Here I am using the simplest way to create a Spring Boot app using Spring Initializer.

Go to https://start.spring.io website, then it will display in build form with many options. See the below screenshot.

Spring Initializer Image

  • Here I am using JDK 17 in my system. So I chose Java version 17. And add Spring Web dependency which downloads all libraries related to the Rest controller and JSON parsers.
  • Then Click the Generate button at the bottom of the page. It will create a maven project and download it to your local as a .zip file. Extract the zip and import it into your IDE.
  • It will take a couple of minutes to download all dependencies which are there in pom.xml. Once downloading is done, your project structure looks like this.

Project Structure

Check the following code as a pom.xml file.

XML




<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.gfg</groupId>
    <artifactId>JsonParamSpringExample</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>JsonParamSpringExample</name>
    <description>Example project for Spring Boot and Json as input param - Geeks For Geeks </description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
  
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
  
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
  
</project>


Check the following code in the PersonController.java file

Java




package com.gfg.jpse.controller;
  
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
  
import com.gfg.jpse.request.Person;
  
@RestController
@RequestMapping("/api/person")
public class PersonController {
  
     @PostMapping("/add")
        public ResponseEntity<String> addPerson(@RequestBody Person person) {
            // Process the person object (save to database, perform business logic, etc.)
            // For simplicity, let's just return a success message and print input json object
            System.out.println(person);
            return new ResponseEntity<>("Person added successfully", HttpStatus.CREATED);
        }
      
}


Explanation of the Above Code:

  • In the above example, we are taking POST API with path URL as /add this method taking Person class as an object and returning ResponseEntity<String>.
  • The @RequestBody annotation is used to bind the incoming JSON data to the Person object.
  • The addPerson method receives a Person object as a parameter, and Spring automatically converts the incoming JSON data to this object.
  • Check the following code in the Person.java file

Java




//Simple entity for Person
  
package com.gfg.jpse.request;
  
public class Person {
  
    private String name;
    private int age;
    private String email;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
      
      
    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + ", email=" + email + "]";
    }
}


Here Person.java class is a Java class that is the same as our JSON file. This class has three variables name, age, and email same as JSON keys. This class just holds the values of JSON keys.

Check the following code in JsonParamSpringExampleApplication.java file

Java




//Spring Boot Application Class
  
package com.gfg.jpse;
  
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
  
//Driver class
@SpringBootApplication
public class JsonParamSpringExampleApplication {
  
      //Main method
    public static void main(String[] args) {
        SpringApplication.run(JsonParamSpringExampleApplication.class, args);
    }
  
}


Check the following code in the application.properties file

server.port=8081

Note:

1. property server.port=8081 has changed the tomcat port to 8081. By default it will run in 8080.
2. If nothing run on 8080 port then no need to add this in application.properties file. Automatically app will take 8080 port to run.
3. If you already run any app in 8080 then you have to modify your port as below.

Testing and Output

Since we created the POST API, we need to test it by using the Postman tool. You can download the Postman tool and install it on your system. Or you can test the API by using curl. I will provide both here.

1. Curl Command

curl --location 'http://localhost:8081/api/person/add' \
--header 'Content-Type: application/json' \
--data-raw '{
"name": "John Doe",
"age": 25,
"email": "john@example.com"
}'

2. POSTMAN

Postman Testing

In IDE open the console and you will be able to see the printing Person object.

Person [name=John Doe, age=25, email=john@example.com]

JSON Parameters with Spring MVC

JSON (JavaScript Object Notation) is a lightweight data exchange format. We can interchange data from one application to another from client to server. We have many data interchange formats available in the market. Like properties files, XML files, YAML files, JSON files, etc. But when compared to others JSON has some special advantages for java related frameworks. In this article, we will learn about How to use JSON Parameters with Spring MVC.

Similar Reads

JSON Parameters with Spring MVC

JSON parameters in Spring MVC facilitate standardized, flexible, and readable communication between clients and servers, especially in the context of building RESTful APIs and modern web applications. It simplifies data exchange, enhances interoperability, and aligns with industry best practices....

JSON Parameters with Spring Boot

In Spring Boot, we can handle JSON parameters in various ways. Here, we will understand a simple example using the @RequestBody annotation to map JSON data to a Java object. Let’s take the below sample JSON format acts as an input for Spring Boot Rest Controller....

Example JSON as Parameter

...

Example: JSON parameter input as @RequestBody

As mentioned above, we will create one sample spring boot app with a POST endpoint. Which takes the Person JSON file as input....