Skip to content

Custom Handlers

Tatu Saloranta edited this page Jun 2, 2015 · 3 revisions

While the main configuration mechanism are the [Standard Features](JSON Features)), there are certain things you can customize by providing custom handers.

All these features are registered by using fluent with(...) method of JSON: result is a new JSON instance, configured to use specified handler. Calls are often chained, and resulting JSON may be cached, reused; or just discarded, as instances are light-weight and there is no overhead being cost of the Object construction itself.

PrettyPrinter

It is possible to configure a standard Jackson streaming PrettyPrinter to use, instead of the default one:

JSON j = JSON.std.with(new CustomPrettyPrinter());

MapBuilder

MapBuilder is a helper object used for construction java.util.Map instances when binding JSON as Maps. One reason would be to use a specialized map like TreeMap, instead of LinkedHashMap; or to provide a more efficient read-only variant for small instances.

JSON j = JSON.std.with(new CustomMapBuilder());

CollectionBuilder

Similar to MapBuilder, it is possible to change kind of java.util.Collection constructed:

JSON j = JSON.std.with(new CustomCollectionBuilder());

Custom Tree Codec

It is possible to register TreeCodec, which would let a Tree Models (like Jackson JsonNode) be recognized and handled automatically by Jackson jr:

JSON j = JSON.std.with(myTreeCodec);

Custom JsonFactory

To change the underlying Streaming API implementation -- for example, to support non-JSON output, like Smile, CBOR or YAML, you can register alternate factory for JSON:

JSON y = JSON.std.with(new YAMLFactory());

Custom JSONReader

While it is not possible to register custom deserializers, it is possible to wholesale replace the handler responsible for binding JSON as Objects: this is what JSONReader entity is for. You can do this by changing default instance used; custom instance has to be a sub-class with suitable overrides:

JSON j = JSON.std.with(new MyJSONReader());

Custom JSONReader

While it is not possible to register custom serializers, it is possible to wholesale replace the handler responsible for writing Objects as JSON: this is what JSONWriter entity is for. You can do this by changing default instance used; custom instance has to be a sub-class with suitable overrides:

JSON j = JSON.std.with(new MyJSONWriter());