Skip to main content

Context Settings

Serializers and parsers have a wide variety of configurable settings. Their builders all extend from the BeanContext.Builder class that allows you to easily construct new instances from scratch or build upon existing instances.

For example, the following code shows how to configure a JSON serializer:

WriterSerializer serializer = JsonSerializer
.create() // Create a JsonSerializer.Builder
.simpleMode() // Simple mode
.ws() // Use whitespace
.sq() // Use single quotes
.sortProperties() // Sort bean properties by name
.build(); // Create a JsonSerializer

However, each of the serializers and parsers already contain reusable instances with common configurations.

For example, JSON has the following predefined reusable serializers and parsers:

JsonSerializerDEFAULTDEFAULT_READABLEJson5SerializerDEFAULT DEFAULT_READABLEJsonParserDEFAULT DEFAULT_STRICT

These can be used directly, as follows:

// Serialize a POJO to LAX JSON.
String json = Json5Serializer.DEFAULT.serialize(myPojo);

For performance reasons, serializers and parsers are immutable. However, they can be 'copied' and modified using the copy() method.

// Clone and customize an existing serializer.
WriterSerializer serializer = Json5Serializer.DEFAULT
.copy() // Create a new builder with copied settings.
.quoteChar('"') // Use a different quote character.
.build();

Default values for configurable settings can be set globally using either system properties or environment variables.

For example, the default useWhitespace setting can be set by either the system property WriterSerializer.useWhitespace or environment variable WRITERSERIALIZER_USEWHITESPACE.

The builder setters will identify when default values can be set this way.