java - Java中的JSON解析错误: Unexpected character at position --

标签 java json parsing

我正在编写一个Java程序,它会遍历当前目录中的所有JSON文件并解析它们,但我在解析部分遇到了问题。我在 JSONObject x 上收到错误行说 Unexpected character (�) at position 0.

但问题是当我手动替换 files[i] 时使用文件目录的字符串,我没有收到错误。我仅在使用 files[i] 时收到错误,但我不明白为什么,因为 files[i]是文件目录的字符串

File path = new File(filePath);
File[] files = path.listFiles();

for (int i = 0; i < files.length; i++) {
    if (files[i].isFile()) {
        //the following line is giving me the error!
        JSONObject x = (JSONObject) parser.parse(new InputStreamReader(new FileInputStream(files[i])));
        org.json.simple.JSONArray contexts = (org.json.simple.JSONArray) x.get("contexts");
        for (int y = 0; y < contexts.size(); y++) {
            Object name = contexts.get(y);
            System.out.println(name);
        }
    }
}

最佳答案

想通了!问题实际上是目录中存在不是 JSON 的文件,因此在尝试解析时会出现错误。现在我删除了非 JSON 文件,不再有错误

关于java - Java中的JSON解析错误: Unexpected character at position --,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48551745/

相关文章:

java - 我应该在 java 或 php 中转换字符串 sha1 吗?

java - 使用 SuperCSV CSVBeanReader 时在字符串上使用什么单元处理器

java - Eclipse 中的多个标记错误

javascript - 使用 Web::Scraper 提取 javascript

java - 面临 JPA 合并问题。合并操作未反射(reflect)在数据库中并且查询执行了两次

ruby-on-rails - 将 ruby​​ 哈希转换为 json 对象

json - 如何将 JSON 从文件加载到 SQL Server 2016 中?

c++ - 构造一个像 JSON 文件一样的字符串 C++

python - 文档开头的 XML 注释

linux - 如何从输出行中提取第一列?