我正在编写一个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/