Read Json from URL
In this article, we will take a look at 3 different ways to read a json string from a url in java. Also, how to convert this json string to a java object.
Use java built-in classes to read json data from a URL.
java.net.URL
class accepts the URL of json resource in string format. It has an openConnection()
method which connects to the resource.Once we have a connection, use its
getInputStream()
method to get access to input stream connected to the resource.Using this input stream, we can read json data line by line using java BufferedReader class.
Example,
URL url = new URL("http://jsonplaceholder.typicode.com/posts/1"); URLConnection connection = url.openConnection(); BufferedReader reader = new BufferedReader( new InputStreamReader( connection.getInputStream())); String line = null; StringBuilder content = new StringBuilder(); while((line = reader.readLine()) != null) { content.append(line).append("\n"); } System.out.println(content);
2. Using Apache Commons
Apache Commons IO library has a org.apache.commons.io.IOUtils
class, having a method toString()
.
It accepts the URL of json resource as a URL
object and returns the json data at this URL as a string. Example,
URL url = new URL("http://jsonplaceholder.typicode.com/posts/1"); String content = IOUtils.toString(url); System.out.println(content);
Apache Commons IO can be added to a project using below Maven or Gradle dependency.
// Maven <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.11.0</version> </dependency> // Gradle implementation 'commons-io:commons-io:2.11.0'
Above methods read a json from URL to a string. But, you might want to convert a json string to a java object.
For this purpose, Google’s gson library will be handy.
It has a fromJson()
method that accepts two arguments
A. Reader object that points to the json resource.
B. Class type to which the json string will be mapped.
Suppose the class to which the json string will be mapped is given below
class Post { private Integer id; private String title; // getters and setters }
Remember that the fields or instance variables of the class should match with the keys of json string. Example,
Post post = new Gson().fromJson( new InputStreamReader(url.openStream()), Post.class);
Convert json string to object
If you need to use the first two methods or you already have a json string and convert it to an object, then you can use below 2 methods
1. Using JSONObject
org.json
is a java library that deals with json objects. It has an org.json.JSONObject
class which converts a json string to json object. Example,
String jsonStr = "{\"id\":1, \"name\":\"Abc\"}"; JSONObject obj = new JSONObject(jsonStr); String name = obj.getString("name");
Its constructor accepts a json string and returns a json object. This object can be used to get values using its get()
methods supplying the name of a key.
2. Using ObjectMapper
Jackson library is the most popular java library for handling json objects. It has an ObjectMapper class, which converts a string to java object. Example,
ObjectMapper mapper = new ObjectMapper(); User user = mapper.readValue(content.toString(), User.class);
Remember that for this method to work, the java class to which the json string needs to be converted should have all the properties corresponding to the keys in json, else it will throw an error.
If you can’t add all the fields to the class, then use any methods outlined in this article to overcome this.