Spring REST service: retrieving JSON from Request

Spring REST service: retrieving JSON from Request

In a Spring REST service, you can retrieve JSON from a request body using the @RequestBody annotation. Here's a basic example:

Let's say you have a simple REST controller:

import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @PostMapping("/jsonEndpoint") public String handleJsonRequest(@RequestBody MyModel myModel) { // Process the JSON data here return "Received JSON: " + myModel.toString(); } } 

In this example:

  • MyModel is a class representing the structure of the JSON data you're expecting. For instance:
public class MyModel { private String field1; private int field2; // getters and setters } 
  • The handleJsonRequest method accepts a MyModel object as a parameter annotated with @RequestBody. When Spring receives a POST request to the /jsonEndpoint endpoint with JSON data in the request body, it will automatically deserialize the JSON data into a MyModel object and pass it to this method.

To test this endpoint, you can use tools like Postman or curl to send a POST request with JSON data in the request body to http://localhost:8080/jsonEndpoint. Here's an example using curl:

curl -X POST \ http://localhost:8080/jsonEndpoint \ -H 'Content-Type: application/json' \ -d '{	"field1": "value1",	"field2": 123 }' 

This sends a POST request to the /jsonEndpoint endpoint with JSON data {"field1": "value1", "field2": 123} in the request body.

Spring will deserialize this JSON data into a MyModel object and pass it to the handleJsonRequest method for further processing.

Examples

  1. Spring REST - Receive JSON Object in Request Body

    Description: Implement a Spring REST endpoint to receive a JSON object in the request body.

    Code:

    import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class JsonController { @PostMapping("/receiveJson") public String receiveJson(@RequestBody MyJsonData jsonData) { // Logic to process JSON data return "Received JSON data: " + jsonData.toString(); } } class MyJsonData { private String field1; private int field2; // Getters and setters } 

    Explanation: Define a POST endpoint /receiveJson in a Spring REST controller (JsonController) to receive JSON data in the request body. Use @PostMapping and @RequestBody annotations to map the JSON data to the jsonData parameter.

  2. Spring Boot - Extract JSON Array from Request Body

    Description: Extract and process a JSON array from the request body in a Spring Boot application.

    Code:

    import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController public class JsonArrayController { @PostMapping("/processJsonArray") public String processJsonArray(@RequestBody List<MyJsonObject> jsonArray) { // Logic to process JSON array return "Processed JSON array: " + jsonArray.toString(); } } class MyJsonObject { private String field1; private int field2; // Getters and setters } 

    Explanation: Define a POST endpoint /processJsonArray in a Spring REST controller (JsonArrayController) to receive and process a JSON array in the request body. Use @PostMapping and @RequestBody annotations to map the JSON array to a List<MyJsonObject>.

  3. Spring MVC - Retrieve JSON Object with Path Variables

    Description: Implement a Spring MVC endpoint to retrieve a JSON object using path variables.

    Code:

    import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class JsonPathVariableController { @GetMapping("/getJson/{id}") public String getJsonById(@PathVariable("id") Long id) { // Logic to retrieve JSON object by ID and return as JSON string return "{\"id\": " + id + ", \"name\": \"John\"}"; } } 

    Explanation: Define a GET endpoint /getJson/{id} in a Spring MVC controller (JsonPathVariableController) to retrieve a JSON object based on the id path variable. Use @GetMapping and @PathVariable annotations to map the id parameter.

  4. Spring REST - Parse JSON String from Request Body

    Description: Parse and process a JSON string from the request body in a Spring REST service.

    Code:

    import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class JsonStringController { @PostMapping("/parseJsonString") public String parseJsonString(@RequestBody String jsonString) { // Logic to parse and process JSON string return "Parsed JSON string: " + jsonString; } } 

    Explanation: Define a POST endpoint /parseJsonString in a Spring REST controller (JsonStringController) to receive and process a JSON string in the request body. Use @PostMapping and @RequestBody annotations to map the JSON string to the jsonString parameter.

  5. Spring Boot - Retrieve Nested JSON Object from Request Body

    Description: Retrieve and handle a nested JSON object from the request body in a Spring Boot application.

    Code:

    import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class NestedJsonObjectController { @PostMapping("/processNestedJson") public String processNestedJson(@RequestBody NestedJsonData nestedData) { // Logic to process nested JSON object return "Processed nested JSON object: " + nestedData.toString(); } } class NestedJsonData { private String parentField; private NestedChild child; // Getters and setters } class NestedChild { private String childField; // Getters and setters } 

    Explanation: Define a POST endpoint /processNestedJson in a Spring REST controller (NestedJsonObjectController) to receive and process a nested JSON object in the request body. Use @PostMapping and @RequestBody annotations to map the JSON object to the NestedJsonData parameter.

  6. Spring MVC - Extract JSON Object Using Request Parameters

    Description: Extract and process a JSON object using request parameters in Spring MVC.

    Code:

    import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class JsonRequestParamsController { @GetMapping("/getJSON") public String getJsonData(@RequestParam("id") Long id, @RequestParam("name") String name) { // Logic to create JSON object based on request parameters return "{\"id\": " + id + ", \"name\": \"" + name + "\"}"; } } 

    Explanation: Define a GET endpoint /getJSON in a Spring MVC controller (JsonRequestParamsController) to retrieve and process a JSON object using request parameters (id and name). Use @GetMapping and @RequestParam annotations to map the parameters.

  7. Spring Boot - Receive JSON Array with Dynamic Structure

    Description: Receive and handle a JSON array with a dynamic structure in a Spring Boot application.

    Code:

    import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; @RestController public class DynamicJsonArrayController { private final ObjectMapper objectMapper = new ObjectMapper(); @PostMapping("/processDynamicArray") public String processDynamicArray(@RequestBody JsonNode jsonArray) { // Logic to process JSON array with dynamic structure return "Processed JSON array: " + jsonArray.toString(); } } 

    Explanation: Define a POST endpoint /processDynamicArray in a Spring REST controller (DynamicJsonArrayController) to receive and process a JSON array with a dynamic structure. Use @PostMapping, @RequestBody, and Jackson's JsonNode to handle the dynamic JSON structure.

  8. Spring REST API - Retrieve JSON Object from HttpServletRequest

    Description: Retrieve and process a JSON object from HttpServletRequest in a Spring REST API.

    Code:

    import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; import java.io.IOException; import java.util.stream.Collectors; @RestController public class JsonRequestFromServletRequestController { @PostMapping("/processJsonRequest") public String processJsonRequest(HttpServletRequest request) throws IOException { String requestBody = request.getReader().lines().collect(Collectors.joining(System.lineSeparator())); // Logic to process JSON request body return "Processed JSON request: " + requestBody; } } 

    Explanation: Define a POST endpoint /processJsonRequest in a Spring REST controller (JsonRequestFromServletRequestController) to retrieve and process a JSON object from HttpServletRequest. Use HttpServletRequest and its getReader() method to read the request body.

  9. Spring Boot - Retrieve JSON Object with UTF-8 Encoding

    Description: Ensure proper retrieval and processing of a JSON object with UTF-8 encoding in Spring Boot.

    Code:

    import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class Utf8JsonController { @PostMapping(value = "/processUtf8Json", produces = "application/json; charset=UTF-8") public String processUtf8Json(@RequestBody String utf8Json) { // Logic to process UTF-8 encoded JSON object return "Processed UTF-8 JSON object: " + utf8Json; } } 

    Explanation: Define a POST endpoint /processUtf8Json in a Spring REST controller (Utf8JsonController) to receive and process a UTF-8 encoded JSON object. Use @PostMapping and @RequestBody annotations, and ensure correct UTF-8 encoding in the produces attribute of @PostMapping.


More Tags

flops android-view hierarchical-clustering tcl react-navigation vulkan mybatis ipa unique-constraint pass-by-reference

More Programming Questions

More Everyday Utility Calculators

More Electronics Circuits Calculators

More Retirement Calculators

More Pregnancy Calculators