Merge pull request #9350 from vikasrajput6035/BAEL-3067

BAEL-3067: Article - Convert BufferedReader to JSONObject - Completed
This commit is contained in:
Josh Cummings 2020-05-30 19:52:06 -06:00 committed by GitHub
commit 14ece4c049
2 changed files with 53 additions and 0 deletions

View File

@ -21,6 +21,11 @@
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20200518</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,48 @@
package com.baeldung.bufferedreadertojsonobject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.junit.Test;
public class JavaBufferedReaderToJSONObjectUnitTest {
@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"));
}
@Test
public void givenValidJson_whenUsingString_thenJSONObjectConverts() throws IOException {
byte[] b = "{ \"name\" : \"John\", \"age\" : 18 }".getBytes(StandardCharsets.UTF_8);
InputStream is = new ByteArrayInputStream(b);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
JSONObject json = new JSONObject(sb.toString());
assertNotNull(json);
assertEquals("John", json.get("name"));
assertEquals(18, json.get("age"));
}
}