JSONParser
解析给定文件中的所有json对象,但我想解析从 100th index 开始到文件末尾的json对象。
我可以稍后使用subList
执行此操作,但如果我的json文件中有 1百万个json对象,我不想解析所有内容,因为效率会降低。
public static void readJsonFile() {
JSONParser parser = new JSONParser();
try {
JSONArray a = (JSONArray) parser.parse(new FileReader("D:\\2018-4-21.json"));
for (Object o : a.subList(100,a.size())) {
JSONObject checkIn = (JSONObject) o;
String userId = (String) checkIn.get("UserID");
System.out.print(userId);
String inout = (String) checkIn.get("INOUT");
System.out.print(" " + inout);
String swippedDateTime = (String) checkIn.get("SwippedDateTime");
System.out.print(" " + swippedDateTime);
System.out.println("");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (org.json.simple.parser.ParseException e) {
e.printStackTrace();
}
}
[
{
"UserID": "2",
"INOUT": null,
"SwippedDateTime": "2018-4-23 22:25"
},
{
"UserID": "2",
"INOUT": null,
"SwippedDateTime": "2018-4-23 22:36"
},
{
"UserID": "2",
"INOUT": null,
"SwippedDateTime": "2018-4-23 22:36"
},
{
"UserID": "2",
"INOUT": null,
"SwippedDateTime": "2018-4-23 22:36"
},
{
"UserID": "2",
"INOUT": null,
"SwippedDateTime": "2018-4-23 22:38"
},
{
"UserID": "2",
"INOUT": null,
"SwippedDateTime": "2018-4-23 22:38"
},
{
"UserID": "2",
"INOUT": null,
"SwippedDateTime": "2018-4-23 22:38"
},
{
"UserID": "2",
"INOUT": null,
"SwippedDateTime": "2018-4-23 22:39"
},
{
"UserID": "2",
"INOUT": null,
"SwippedDateTime": "2018-4-23 22:39"
},
{
"UserID": "2",
"INOUT": null,
"SwippedDateTime": "2018-4-23 22:39"
},
{
"UserID": "2",
"INOUT": null,
"SwippedDateTime": "2018-4-23 22:42"
},
{
"UserID": "2",
"INOUT": null,
"SwippedDateTime": "2018-4-23 22:42"
},
{
"UserID": "2",
"INOUT": null,
"SwippedDateTime": "2018-4-23 22:42"
},
{
"UserID": "2",
"INOUT": null,
"SwippedDateTime": "2018-4-23 22:42"
},
{
"UserID": "2",
"INOUT": null,
"SwippedDateTime": "2018-4-23 22:42"
},
{
"UserID": "2",
"INOUT": null,
"SwippedDateTime": "2018-4-23 22:42"
},
{
"UserID": "2",
"INOUT": null,
"SwippedDateTime": "2018-4-23 22:49"
}
]
答案 0 :(得分:2)
找到索引100的唯一方法是解析一切到索引100。
我认为你真正要求的是如何在不在内存中创建不必要的对象的情况下做到这一点。
答案实际上也可以帮助您管理具有数百万条记录的文件,而不会耗尽内存:
使用流式解析器。
使用流解析器,您将在解析数据时获取数据,因此您可以快速跳过前X个记录,然后一次开始处理一个记录,这样您就不必在内存中保留多个记录。
这意味着您实际上可以解析内容占用空间非常小的无限大小的文件。
由于您使用的是GSON,这意味着您需要使用JsonReader
代替JsonParser
。
答案 1 :(得分:0)
如果您有1,000,000条记录,则需要考虑内存使用情况。
执行此操作的最有效方法是手动读取文件的第一部分 - 如果您已显示,则所有记录的大小相同,因此您只需使用InputStream.skip()
- 当然,如果像UserID
这样的字符串字段可以有不同的长度,那么这将不起作用。
您可以逐个字符地阅读文件,计算(说)逗号以确定您何时跳过100条记录。
在您跳过文件的第一部分后,您应该使用流解析器来阅读其余部分。 Gson会这样做:https://sites.google.com/site/gson/streaming
您还可以使用流解析器有效地跳过文件的第一部分。