我在 JSON
中有 1 亿条记录文件,需要一种有效且最快的方法来从 JSON
中读取数组数组文件在 java
.
JSON
文件看起来像:
[["XYZ",...,"ABC"],["XYZ",...,"ABC"],["XYZ",...,"ABC"],...,["XYZ",...,"ABC"],
["XYZ",...,"ABC"],["XYZ",...,"ABC"],["XYZ",...,"ABC"],...,["XYZ",...,"ABC"],
...
...
...
,["XYZ",...,"ABC"],["XYZ",...,"ABC"],["XYZ",...,"ABC"]]
我想读这个JSON
逐行归档为:
先阅读:
["XYZ",...,"ABC"]
然后:
["XYZ",...,"ABC"]
等等:'
...
...
...
["XYZ",...,"ABC"]
我如何阅读 JSON
像这样的文件,我知道它看起来并不完全像 JSON
文件,但我需要以这种格式读取此文件,该文件另存为 .JSON
最佳答案
您可以使用 JSON Processing API (JSR 353) , 以流式处理您的数据:
import javax.json.Json;
import javax.json.stream.JsonParser;
...
String dataPath = "data.json";
try(JsonParser parser = Json.createParser(new FileReader(dataPath))) {
List<String> row = new ArrayList<>();
while(parser.hasNext()) {
JsonParser.Event event = parser.next();
switch(event) {
case START_ARRAY:
continue;
case VALUE_STRING:
row.add(parser.getString());
break;
case END_ARRAY:
if(!row.isEmpty()) {
//Do something with the current row of data
System.out.println(row);
//Reset it (prepare for the new row)
row.clear();
}
break;
default:
throw new IllegalStateException("Unexpected JSON event: " + event);
}
}
}
关于java - 在 Java 中逐行读取大型 JSON 文件的快速高效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43328372/