Skip to content

Building, Streaming and Manipulating Nodes

Jan Bernitt edited this page Jan 25, 2024 · 3 revisions

Warning

The documentation below has not been updated to the newest version

Building Nodes Ad-hoc

The JsonBuilder API is used to:

  • create a JsonNode document (and from there a JSON String)
  • directly stream JSON to an output stream while it is built

While it is an "append-only" API to support true streaming its use of lambda function arguments allows to compose the output in a convenient and flexible way.

Ad-hoc creation of JsonNode:

JsonNode obj = JsonBuilder.createObject(obj -> obj.addString( "name","value" ));
    
String json = obj.getDeclaration();

Writing Nodes to a Stream

Directly writing JSON to an output stream:

JsonBuilder.streamObject( out, obj -> obj.addString( "name", "value" ) );

Manipulating JSON Trees

The JsonNode trees are effectively immutable tree structures. However, they can be "manipulated" returning a new changed tree root.

To replace any type of node with a different node use JsonNode#replaceWith. The new JSON String provided is expected to be valid JSON. To add members to an object node JsonNode#addMember is used, again expecting value name and JSON value. Both return a new changed root.

If only a subtree of an existing tree should be extracted use JsonNode#extract();

OBS! This technique should be used with care it each changes produces a new tree that needs to be parsed again.

Clone this wiki locally