我有一个简单的Java应用程序,它需要遍历一个大型JSON数组(包含约2万个项目),并且在每个数组中,我解析一个子数组。每个项目如下所示:
Java
JSON
{"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个项目)。
JSONPath
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简单的样子:
HASHMap
ArrayList<HashMap> json= JsonPath.read(response, "$.result");
然后我们可以简单地调用get(i)以访问循环中的特定项目:
get(i)
double start_time = (double) json.get(i).get("startTime");