Explain Codes LogoExplain Codes Logo

Simplest way to read JSON from a URL in Java

java
exception-handling
json-parsing
maven-dependency-management
Anton ShumikhinbyAnton Shumikhin·Dec 8, 2024
TLDR

Fetch JSON from a URL in Java using HttpClient and parse it with JsonObject. Here it goes:

import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonReader; HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder().uri(URI.create("YOUR_URL")).build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); try (JsonReader jsonReader = Json.createReader(new StringReader(response.body()))) { JsonObject json = jsonReader.readObject(); System.out.println(json); }

Swap "YOUR_URL" with the JSON source URL. Remember to handle exceptions as needed.

Deep Dive: The Nitty-Gritty Details

Bullet-proof your code: Exception Handling

To ensure stability and error-proofness, opt for comprehensive exception handling. Here's a version of the snippet with error handling baked-in:

// Catch 'em all (IOExceptions, that is!) try { HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); try (JsonReader jsonReader = Json.createReader(new StringReader(response.body()))) { JsonObject json = jsonReader.readObject(); System.out.println(json); } } catch (IOException | InterruptedException e) { e.printStackTrace(); // This is where we whimper in a corner! }

Aptly Fetching URL Content

Why groan over repetition when you can streamline your content fetching with Apache Commons IOUtils? One line. That's all it takes:

String jsonContent = IOUtils.toString(new URL("YOUR_URL"), StandardCharsets.UTF_8); // Bazinga!

Parsing JSON without breaking a sweat

Now that you have the JSON content, use a parsing library like org.json:json or Jackson to convert it into a Java object:

JSONObject jsonObject = new JSONObject(jsonContent); // Yep, just like that. No kidding.

Charset Handiwork

Be attentive to character encoding. Trust me, you don't want to mess with them! Use Charset.forName("UTF-8"):

String jsonContent = IOUtils.toString(new URL("YOUR_URL"), Charset.forName("UTF-8")); // Now we're talking!

Going the Extra Mile

Finer Control with URLConnection

Need more control over your HTTP connections? URLConnection is your friend. It's the swiss army knife for handling advanced HTTP features and customizable requests:

// "URLConnection - When HttpClient is too mainstream!" HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); // BufferedReader - because we read things, not stare at them! try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { StringBuilder jsonString = new StringBuilder(); // StringBuilder, because stroking a cat was easier than dealing with StringBuffer! for (String line; (line = reader.readLine()) != null; ) { jsonString.append(line); } JSONObject json = new JSONObject(jsonString.toString()); System.out.println(json); }

Resource Management: Because no one likes leaks

Always close streams and connections when you're done. try-with-resources is safety goggles for your code:

try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { // Do your thing! }

Extracting Data: The Secret Decoder

Just use the keys in the JSON object to craftily extract the data you're after:

String value = json.getString("yourKey"); // Your key to the treasure!

Maven Dependency Management: Organize your Tool kit

Using org.json:json or libraries like Jackson? Here's how you tuck them neatly in your Maven pom.xml:

<dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20210307</version> </dependency>

ObjectMapper: The magic wand

Jackson's ObjectMapper can convert JSON to Java object and vice versa like a pro, proving to be a boon for direct mapping and error handling:

ObjectMapper mapper = new ObjectMapper(); YourClass obj = mapper.readValue(jsonContent, YourClass.class); // Voila! That's some real sorcery!