[英]How to determine the size of json array using `com.fasterxml.jackson.core.JsonParser`
I am using an internal library which exposes an api, to parse a json value.我正在使用公开 api 的内部库来解析 json 值。 This api provides
com.fasterxml.jackson.core.JsonParser
to make use of, which is already instantiated with the appropriate json stream to be read. This api provides
com.fasterxml.jackson.core.JsonParser
to make use of, which is already instantiated with the appropriate json stream to be read. Now, how do I determine the size of an array, assuming the json stream this JsonParser instance is parsing is an array object.现在,我如何确定数组的大小,假设 json stream 这个 JsonParser 实例正在解析的是一个数组 object。
I can find a way by instantiating an ObjectMapper using this JsonParser instance, and create a container java class with a list in it (representing the array) and finally determine the size.我可以通过使用此 JsonParser 实例实例化 ObjectMapper 找到一种方法,并创建一个容器 java class ,其中包含一个列表(表示数组),最后确定大小。 I was wondering if its possible to do it just with JsonParser without using ObjectMapper.
我想知道是否可以只使用 JsonParser 而不使用 ObjectMapper。
class ResultContainer {
private List<Object> result;
public List<Object> getResult() {
return result;
}
public void setResult(List<Object> result) {
this.result = result;
}
}
----
void parseEntity(JsonParser parser) {
ObjectMapper om = new ObjectMapper();
ResultContainer rc = om.readValue(parser, ResultContainer.class);
System.out.println(rc.getResult().size());
}
In the above example, is there a way I can get the size of the array with just the JsonParser, without using ObjectMapper and therefore without creating a dummy container java class.在上面的示例中,有没有一种方法可以仅使用 JsonParser 获取数组的大小,而无需使用 ObjectMapper,因此无需创建虚拟容器 java class。
Sure, you can read JSON into JsonNode
: https://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/ObjectMapper.html Sure, you can read JSON into
JsonNode
: https://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/ObjectMapper.html
JsonNode root = mapper.readTree(...);
and then analyze this JsonNode
.然后分析这个
JsonNode
。 Take a look at examples: https://www.baeldung.com/jackson-json-node-tree-model#2-handling-different-node-types看看例子: https://www.baeldung.com/jackson-json-node-tree-model#2-handling-different-node-types
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.