Jackson 2.10 feature: JsonNode improvements

Handling of JsonNode (base class of Tree Model representation in Jackson) was significantly improved in Jackson 2.10 as mentioned in “Jackson 2.10 features” overview. But due to space constraints overview did not dig very deep. Let’s have another look at what was added.

JsonNode.toString() is now supported

Although users sometimes used toString() implementation of JsonNode values, this was actually not supported usage by Jackson. Usage was unsupported because it was implemented so that:

  1. Writing as JSON-like output was implemented inefficiently so using it for large documents would be wasteful as well as possibly incorrect.

JsonNode is now java.io.Serializable

Although JsonNode values are naturally serializable — that is, just write out as JSON — some frameworks (such as Spark, Flink and Hadoop) use JDK Serializability for transferring configuration objects, and sometimes even data (although for data it is typically not a good choice).

Convenient Validating Traversal methods for JsonNode

After working on refactoring test code that uses Jackson’s JsonNode for verifying correctness of REST API request and response payloads, I came to miss ability to use “validating” accessors: methods that will access or traverse Tree hierarchy, but also verify assertions while doing this.

JsonNode root = ...;
JsonNode value = root.path("data").path("x");
if (value.isMissingNode()) {
throw new IllegalArgumentException("No value /data/x");
}
int x = value.asInt();
int x = root.requiredAt("/data/x").asInt();
// or, for longer
x = root.path("data").path("x").require();
{ "data" : {
"x" : 42
}}
{ "data" : {
"value" : 42
}}
  1. required(String) (for Object nodes), required(int) (for Array nodes), requiredAt(JsonPointer) (for arbitrary paths through Objects and/or Arrays), that are short-hand combinations of traversal followed by require() on result node

Written by

Open Source developer, most known for Jackson data processor (nee “JSON library”), author of many, many other OSS libraries for Java, from ClassMate to Woodstox

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store