W3docs

Get a JSON object from a HTTP response

To get a JSON object from a HTTP response in Java, you can use the JSONObject class from the org.json library.

To get a JSON object from an HTTP response in Java, you can use the JSONObject class from the org.json library along with the built-in java.net.http.HttpClient (Java 11+).

Here is an example of how to fetch a response and parse it into a JSONObject:

import org.json.JSONObject;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://api.example.com/data"))
        .GET()
        .build();

try (HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString())) {
    if (response.statusCode() == 200) {
        JSONObject json = new JSONObject(response.body());
        String name = json.getString("name"); // extract a specific field
        System.out.println("Name: " + name);
    }
} catch (Exception e) {
    e.printStackTrace();
}

In this example, HttpClient.newHttpClient() creates a client, and client.send() executes the request. The try-with-resources block ensures the response is properly closed to prevent connection leaks. response.body() returns the response content as a string, which is passed to the JSONObject constructor to create the object.

You can then use the various methods of the JSONObject class to access the data. For example, you can use getString("fieldName") to get the value of a specific field, or the keys() method to get an iterator over the field names in the object.

I hope this helps! Let me know if you have any other questions.