> For the complete documentation index, see [llms.txt](https://codewithmeiy.gitbook.io/core-java/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://codewithmeiy.gitbook.io/core-java/servlets/json-req-res.md).

# JSON Req/Res

Creating REST APIs in Java using servlets is a common approach for building web services. I'll provide you with an example of creating a simple REST API using a Java servlet that accepts JSON input and returns a JSON response. In this example, we will use the `org.json` library for handling JSON.

1. First, ensure you have the `org.json` library in your classpath, as mentioned in a previous response.
2. Create a Java servlet that handles JSON input and produces a JSON response. Here's a basic example:

```java
import org.json.JSONObject;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

public class JsonApiServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // Read the JSON input from the request
        BufferedReader reader = request.getReader();
        StringBuilder jsonInput = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            jsonInput.append(line);
        }

        // Parse the JSON input using the org.json library
        JSONObject requestBody = new JSONObject(jsonInput.toString());

        // Process the JSON data
        String name = requestBody.getString("name");
        int age = requestBody.getInt("age");

        // Create a JSON response
        JSONObject jsonResponse = new JSONObject();
        jsonResponse.put("message", "Received JSON data");
        jsonResponse.put("name", name);
        jsonResponse.put("age", age);

        // Set the response content type to JSON
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        // Send the JSON response
        try (PrintWriter out = response.getWriter()) {
            out.print(jsonResponse.toString());
        }
    }
}
```

In this example, we have created a servlet that listens to the `POST` requests at the URL `/api/example`. It reads the JSON input from the request and processes it using the `org.json` library. Then, it constructs a JSON response and sends it back to the client.

3. Deploy your servlet in a servlet container like Apache Tomcat.
4. To test the REST API, you can use tools like `curl`, Postman, or a web application that can make HTTP POST requests with a JSON payload. Here's an example using `curl`:

```bash
curl -X POST http://localhost:8080/your-web-app-name/api/example -H "Content-Type: application/json" -d '{"name":"John","age":30}'
```

This `curl` command sends a POST request with a JSON payload to your servlet, and you should receive a JSON response in return.

Please make sure to adapt the code and URL paths to your specific project and deployment setup. This example is for demonstration purposes, and in a production application, you may want to include error handling and additional validation.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://codewithmeiy.gitbook.io/core-java/servlets/json-req-res.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
