To fetch JSON data in Java, we typically use libraries like java.net
for HTTP requests and a JSON parsing library like org.json
, Gson
, or Jackson
to parse the JSON data. Below is an example using HttpURLConnection
from the java.net
package to fetch JSON data from a URL and parse it using the org.json
library.
Fetching JSON Data Using Java:
Here’s a simple example using HttpURLConnection
and org.json
:
- Add Dependencies: If we’re using Maven, add the following dependency for
org.json
:<dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20230227</version> </dependency>
If not using Maven, make sure to download and add the library to your classpath.
- Java Code:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import org.json.JSONObject; public class FetchJsonData { public static void main(String[] args) { String urlString = "https://api.example.com/data"; // Replace with your URL try { // Create URL object URL url = new URL(urlString); // Open a connection HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); // Check if the request was successful if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } // Read the response BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); StringBuilder response = new StringBuilder(); String output; while ((output = br.readLine()) != null) { response.append(output); } // Close the connection conn.disconnect(); // Parse JSON response JSONObject jsonResponse = new JSONObject(response.toString()); // Example of accessing data from JSON System.out.println("Response: " + jsonResponse.toString(2)); // Pretty print JSON with indentation of 2 } catch (Exception e) { e.printStackTrace(); } } }
Key Points:
HTTP Request: The code uses
HttpURLConnection
to make an HTTP GET request to the specified URL. - Reading Response: It reads the response from the server using
BufferedReader
.
- Parsing JSON: The response is parsed into a
JSONObject
using theorg.json
library. - Handling Errors: Make sure to handle exceptions like
IOException
and check the response code to ensure the request was successful.