Configurable Properties
Serializers and parsers have a wide variety of configurable properties.
They all extend from the {@link oaj.BeanContextBuilder} 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 s = JsonSerializer
.create() // Create a JsonSerializerBuilder
.simple() // Simple mode
.ws() // Use whitespace
.sq() // Use single quotes
.build(); // Create a JsonSerializer
Configurable settings can also be set declaratively.
The following produces the same serializer.
WriterSerializer s = JsonSerializer
.create()
.set(JSON_simpleMode, true)
.set(SERIALIZER_useWhitespace, true)
.set(SERIALIZER_quoteChar, "'")
.build();
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:
- {@link oaj.json.JsonSerializer}
- {@link oaj.json.JsonSerializer#DEFAULT DEFAULT}
- {@link oaj.json.JsonSerializer#DEFAULT_READABLE DEFAULT_READABLE}
- {@link oaj.json.SimpleJsonSerializer}
- {@link oaj.json.SimpleJsonSerializer#DEFAULT DEFAULT}
- {@link oaj.json.SimpleJsonSerializer#DEFAULT_READABLE DEFAULT_READABLE}
- {@link oaj.json.JsonParser}
- {@link oaj.json.JsonParser#DEFAULT DEFAULT}
- {@link oaj.json.JsonParser#DEFAULT_STRICT DEFAULT_STRICT}
These can be used directly, as follows:
// Serialize a POJO to LAX JSON.
String json = SimpleJsonSerializer.DEFAULT.serialize(myPojo);
For performance reasons, serializers and parsers are immutable.
However, they can be 'copied' and modified using the builder()
method.
// Clone and customize an existing serializer.
WriterSerializer s = SimpleJsonSerializer.DEFAULT
.builder() // Create a new builder with copied settings.
.quoteChar('"') // Use a different quote character.
.build();