Get Count of json key using Java Stream

 

问题

https://stackoverflow.com/questions/67016736/get-count-of-json-key-using-java-stream

I have a json object that looks like this

[{

"startAt": 1617605301292,

"endAt": 1617605317095,

"duration": 15803,

"selection": {

"selected.Speed": "0",

"selected.Low": "65535",

"selected.Fast": "7173",

"selected.medium": "5"

},

"details": {

"phase": [{

"value": "2",

"timestamp": 1617605301316

}]

}

},

{

"startAt": 1617603849697,

"endAt": 1617603966378,

"duration": 116681,

"selection": {

"selected.Speed": "0",

"selected.Low": "65535",

"selected.Fast": "123",

"selected.medium": "5"

},

"details": {

"phase": [{

"value": "2",

"timestamp": 1617603849749

}]

}

}

]

I need to count how many times selected.Fast has occurred. I am trying with stream and this is what I have written so far

List<Map<String, Object>> jsonObj = mapper.readValue(jArr, new TypeReference<List<Map<String, Object>>>(){});

Map<String, Long> counted = jsonObj.stream()

.map(x -> x.get("selection").toString() )

.collect(Collectors.toList())

.stream()

.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

System.out.println(counted.toString());

But I am getting count of all the key inside selection object, and I want count for specific Json key which isselected.FastFor Exampleselected.Fast:"7173" -> occurred - 5times selected.Fast:"123" -> occurred - 2times

Any help would be appreciated.

解答

将不确定层级的json记录,输出所有层级的字段名。用Java 实现代码较长。

Java 下的开源包 SPL 很容易写,只要 1 句:


A

1

=json(file("data.json").read()).groups(#4.#3;count(~)).("selected.Fast:\""/#1/"\"-> occurred -"/#2/"times")

SPL 提供了 JDBC 供 Java 调用,把上面的脚本存为 count.splx,在 Java 中以存储过程的方式调用脚本文件:

Class.forName("com.esproc.jdbc.InternalDriver");

con= DriverManager.getConnection("jdbc:esproc:local://");

st = con.prepareCall("call count()");
st.execute();

SPL 源代码:https://github.com/SPLWare/esProc

问答搜集