我正在使用 Jackson 对象映射器 (com.fasterxml.jackson.databind.ObjectMapper) 来解析 json 字符串,并且需要计算字符串中出现“路径”一词的次数。字符串看起来像:
"rows":[{"path":{"uid":"2"},"fields":[]},{"path":{"uid":"4"},"fields":[]},{"path":{"uid":"12"},....
有谁知道哪个 API 选项对于实现这一目标最有效?
要计算 'rows' 根目录中的 'childs' 总数,可以使用如下代码:
String inputJsonString = "{\"rows\":[{\"path\":{\"uid\":\"2\"},\"fields\":[]},{\"path\":{\"uid\":\"4\"},\"fields\":[]},{\"path\":{\"uid\":\"12\"},\"fields\":[]}]}";
ObjectNode root = (ObjectNode) new ObjectMapper().readTree( inputJsonString );
root.get( "rows" ).size();
如果您需要获得“路径”出现的确切计数,您可以使用如下代码:
int counter = 0;
for( Iterator<JsonNode> i = root.get( "rows" ).iterator(); i.hasNext(); )
if( i.next().has( "path" ) )
counter++;
System.out.println(counter);