1. Overview
In this quick tutorial, we're going to show how to convert a BufferedReader to a JSONObject using two different approaches.
2. Dependency
Before we get started, we need to add the org.json dependency into our pom.xml:
<dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20200518</version> </dependency>
3. JSONTokener
The latest version of the org.json library comes with a JSONTokener constructor. It directly accepts a Reader as a parameter.
So, let's convert a BufferedReader to a JSONObject using that:
@Test public void givenValidJson_whenUsingBufferedReader_thenJSONTokenerConverts() { byte[] b = "{ \"name\" : \"John\", \"age\" : 18 }".getBytes(StandardCharsets.UTF_8); InputStream is = new ByteArrayInputStream(b); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is)); JSONTokener tokener = new JSONTokener(bufferedReader); JSONObject json = new JSONObject(tokener); assertNotNull(json); assertEquals("John", json.get("name")); assertEquals(18, json.get("age")); }
4. First Convert to String
Now, let's look at another approach to obtain the JSONObject by first converting a BufferedReader to a String.
This approach can be used when working in an older version of org.json:
@Test public void givenValidJson_whenUsingString_thenJSONObjectConverts() throws IOException { // ... retrieve BufferedReader<br /> StringBuilder sb = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { sb.append(line); } JSONObject json = new JSONObject(sb.toString()); // ... same checks as before }
Here, we're converting a BufferedReader to a String and then we're using the JSONObject constructor to convert a String to a JSONObject.
5. Conclusion
In this article, we've seen two different ways of converting a BufferedReader to a JSONObject with simple examples. Undoubtedly, the latest version of org.json provides a neat and clean way of converting a BufferedReader to a JSONObject with fewer lines of code.
As always, the full source code of the example is available over on GitHub.