Search code examples
javajsonparsingjacksonfasterxml

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. 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.

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. I was wondering if its possible to do it just with JsonParser without using 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.


Solution

  • 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. Take a look at examples: https://www.baeldung.com/jackson-json-node-tree-model#2-handling-different-node-types