-
Servlet+JSON parsing library : If you use traditional servlet development, you can obtain the input stream of the request body and use JSON parsing libraries (such as Jackson, Gson, etc.) to convert JSON strings into Java objects. The example code is as follows:
import com.fasterxml.jackson.databind.ObjectMapper; // ...
protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Get the input stream of the request body
BufferedReader reader = request.getReader(); StringBuilder jsonBuilder = new StringBuilder (); String line; while ((line = reader.readLine()) != null ) { jsonBuilder.append(line); } reader.close(); //Parse JSON string
ObjectMapper objectMapper = new ObjectMapper (); YourDTOObject dtoObject = objectMapper.readValue(jsonBuilder.toString(), YourDTOObject.class); //Get Data
String name = dtoObject.getName(); int age = dtoObject.getAge(); // ... }
-
Spring MVC : If you use the Spring MVC framework, you can use its annotations to automatically bind JSON data to Java objects. The example code is as follows:
@RestController
public class YourController { @PostMapping("/your-url")
public void handleJsonRequest ( @RequestBody YourDTOObject dtoObject) { //Get Data
String name = dtoObject.getName(); int age = dtoObject.getAge(); // ... } }