使用 JSONPath 迭代大型 JSON 数组 [英] Iterate over a large JSON Array with JSONPath
问题描述
我有一个简单的 Java
应用程序,它需要遍历一个大的 JSON
数组(大约有 20K 项),并且在每个数组中,我解析一个子数组.每个项目看起来像这样:
I have a simple Java
app that needs to traverse a large JSON
array (with around 20K items), and within each array, I parse a sub-array. Each item looks like this:
{"index":0,"f1":[2,16,16,16,16,16,32,16],"f2":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"startTime":0.0}
我正在使用 JSONPath
迭代每个项目.我所做的是首先读取长度,然后简单地遍历整个数组.但它非常慢(比如,每秒 1 个项目).
I am using JSONPath
to iterate over each item. What I do is first I read the length, and simply iterate over the whole array. But it is very slow (like, 1 item per second).
int length = JsonPath.read(response, "$.result.length()");
for (int i = 0; i < length; i++) {
double start_time = JsonPath.read(response, "$.result["+i+"].startTime");
ArrayList<Integer> f1= JsonPath.read(response, "$.result["+i+"].f1");
//...other things
}
有没有优化的方法?
推荐答案
明白了.感谢 Erwin,我可以像这样一次性将整个 JSON 解析为 HASHMap
:
Got it. Thanks to Erwin, I can parse the whole JSON at once into a HASHMap
simply like this:
ArrayList<HashMap> json= JsonPath.read(response, "$.result");
然后我们可以简单地调用 get(i)
来访问循环中的特定项目:
And then we can simply call get(i)
to access a specific item in the loop:
double start_time = (double) json.get(i).get("startTime");
这篇关于使用 JSONPath 迭代大型 JSON 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!