Converting a BufferedReader to a JSONObject – 将缓冲读卡器转换为JSON对象

最后修改: 2020年 5月 31日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this quick tutorial, we’re going to show how to convert a BufferedReader to a JSONObject using two different approaches.

在这个快速教程中,我们将展示如何BufferedReader转换为JSONObject 使用两种不同方法

2. Dependency

2.依赖性

Before we get started, we need to add the org.json dependency into our pom.xml:

在我们开始之前,我们需要org.json依赖关系添加到我们的pom.xml

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20200518</version>
</dependency>

3. JSONTokener

JSONTokener 3.

The latest version of the org.json library comes with a JSONTokener constructor. It directly accepts a Reader as a parameter.

最新版本的org.json库带有一个JSONTokener构造函数。它直接接受一个Reader作为参数。

So, let’s convert a BufferedReader to a JSONObject using that:

因此,让我们使用这个方法将BufferedReader转换为JSONObject

@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

4.首先转换为字符串

Now, let’s look at another approach to obtain the JSONObject by first converting a BufferedReader to a String.

现在,让我们看看另一种获得JSONObject的方法,首先将一个BufferedReader转换为一个String

This approach can be used when working in an older version of org.json:

当在旧版本的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.

在这里,我们BufferedReader转换为String,然后我们使用JSONObject构造函数将String转换成JSONObject

/wp:段落 wp:标题

5. Conclusion

5.总结

/wp:标题 wp:段落

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.

在这篇文章中,我们通过简单的例子看到了将BufferedReader转换为JSONObject的两种不同方法。毫无疑问,最新版本的org.json提供了一种整洁的方法,可以用较少的代码行将BufferedReader转换为JSONObject

/wp:段落 wp:段落

/wp:段落 wp:段落

As always, the full source code of the example is available over on GitHub.

一如既往,该示例的完整源代码可在GitHub上获取