Simplest way to read JSON from a URL in Java
To read JSON from a URL in Java, you can use the readJsonFromUrl()
method from the JSON simple
library. The JSON simple
library is a lightweight Java library that provides simple and efficient methods for reading and writing JSON.
Here is an example of how you can use the readJsonFromUrl()
method to read JSON from a URL:
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class Main {
public static void main(String[] args) throws IOException, ParseException {
URL url = new URL("http://example.com/json");
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(new InputStreamReader(url.openStream()));
}
}
This code opens a connection to the URL, reads the JSON from the URL, and parses the JSON using the JSONParser
class. The JSONObject
class represents a JSON object, and you can use it to access the properties of the JSON object.
You can also use the IOUtils.toString()
method from the Apache Commons IO
library to read the JSON from the URL as a string:
import org.json.JSONObject;
import org.json.JSONTokener;
import org.apache.commons.io.IOUtils;
import java.net.URL;
public class Main {
public static void main(String[] args) throws IOException {
URL url = new URL("http://example.com/json");
String json = IOUtils.toString(url, "UTF-8");
JSONObject object = new JSONObject(new JSONTokener(json));
}
}
This code reads the JSON from the URL as a string, and then uses the JSONObject
class from the org.json
library to parse the JSON.
I hope this helps! Let me know if you have any other questions.