Skip to content

Instantly share code, notes, and snippets.

@niftycode
Last active April 16, 2021 08:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niftycode/2ae34e009168f96241f773b3f33ef7c3 to your computer and use it in GitHub Desktop.
Save niftycode/2ae34e009168f96241f773b3f33ef7c3 to your computer and use it in GitHub Desktop.
Example how to fetch and parse JSON data in Java 11+
package de.niftycode;
import org.json.JSONArray;
import org.json.JSONObject;
import java.net.URI;
import java.net.http.HttpClient; // < New in Java 11, can also handle HTTP/2 requests!
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
/*
Send HTTP requests using the new API
(Java 11 and above)
This example uses the new java.net.HttpClient which handles
asynchronous operations automatically.
*/
public class Main {
public static void main(String[] args) {
String url = "https://xern-statistic.de/api/countries";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.build();
try {
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenApply(Main::parse)
.join();
} catch(Exception e) {
System.out.println("ERROR!");
System.out.println(e);
}
}
public static String parse(String responseBody) {
JSONArray nations = new JSONArray(responseBody);
try {
for (int i = 0; i < nations.length(); i++) {
JSONObject nation = nations.getJSONObject(i);
String country = nation.getString("country");
String capital = nation.getString("capital");
String government = nation.getString("government");
int population = nation.getInt("population");
System.out.println("Country: " + country);
System.out.println("Capital: " + capital);
System.out.println("Government: " + government);
System.out.println("Population: " + population);
System.out.println("---");
}
} catch(Exception e){
System.out.println(e);
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment