BAEL-3067: Article - Convert BufferedReader to JSONObject - Completed

This commit is contained in:
Vikas Ramsingh Rajput 2020-05-24 10:33:17 +03:00
parent f48582cfe1
commit 05a4d4e188
2 changed files with 53 additions and 0 deletions

View File

@ -22,6 +22,11 @@
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20190722</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 givenUsingNewVersion_whenConvertBufferedReaderToJSONObject_thenCorrect() {
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 givenUsingOldVersion_whenConvertBufferedReaderToJSONObject_thenCorrect() 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"));
}
}