如何在 Java 中将 simple.JSONArray 转换为普通的 JSONArray

问题描述

我正在编写一个 JAVA 程序来读取 JSON 文件数据并进行一些处理。 为了从我的类路径资源文件夹中读取 JSON 文件数据,我使用了以下代码:

import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

String filePath = "src/main/resources/SampleRequest.json";
JSONParser parser = new JSONParser();
Object object = parser.parse(new FileReader(filePath));
JSONArray inputjsonArr = (JSONArray) object;

正如我们所见,我正在使用 import org.json.simple.JSONArray 来读取和获取数据。相反,我尝试直接使用普通的 JSONArray 导入 import org.json.JSONArray; 然后我得到错误:

Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.JSONArray

我想知道是否可以将 simple.JSONArray 转换为普通的 JSONArray。或者我是否可以使用直接 import org.json.JSONArray; 从 JSON 文件中读取数据,以便我根本不必处理这种转换。

解决方法

org.json.simpleorg.json 是不同且不兼容的库。

不应推荐使用 org.json.simple,因为它以 Object 的形式返回其所有值,而 org.json 允许指定要返回的 type

解决方案不是使用 org.json.simple.parser.JSONParser(删除所有 org.json.simple 导入)而是从相关文件中读取字符串并将其直接传递给 org.json.JSONArray,就像这样:

String json = FileUtils.readFileToString(new File( "src/main/resources/SampleRequest.json"),"UTF-8" );
JSONArray array = new JSONArray(json);

如您所见,为简单起见,我喜欢使用以下包中的 FileUtils,因此添加此依赖项:

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.8.0</version>
</dependency>

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...