Skip to main content

Context Settings

Serializers and parsers have a wide variety of configurable settings. Their builders all extend from the MarshallingContext.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.write(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.

Per-Session Property Reference​

The settings above are context-level — baked into an immutable serializer/parser when it is built. Many of the same settings can also be overridden per-request at the session level via Session.Builder.property(String, Object), without rebuilding the context. See Serializers and Parsers for the override mechanism (short vs. fully-qualified property names, automatic string coercion, and REST integration).

The tables below are the complete catalog of per-session properties, grounded in the MarshallingSession hierarchy and its serializer/parser session subclasses (SerializerSession, ParserSession, WriterSerializerSession, and the per-format session classes).

Base Session Properties​

These properties are available on all sessions regardless of format:

PropertyTypeSession ClassDescription
locale / MarshallingSession.localeLocaleMarshallingSessionLocale used for date/number formatting
timeZone / MarshallingSession.timeZoneTimeZoneMarshallingSessionTime zone used for date/calendar types
mediaType / MarshallingSession.mediaTypeMediaTypeMarshallingSessionThe media type being produced or consumed
debugBooleanContextSessionEnable debug mode

Serializer Session Properties​

These properties apply to all serializers:

PropertyTypeSession ClassDescription
addBeanTypesbooleanSerializerSessionAdd _type properties to beans when type cannot be inferred from reflection
addRootTypebooleanSerializerSessionAdd _type to the root object
keepNullPropertiesbooleanSerializerSessionSerialize null bean properties (default: false)
trimStringsbooleanSerializerSessionTrim whitespace from serialized strings
sortCollectionsbooleanSerializerSessionSort collections before serializing
sortMapsbooleanSerializerSessionSort maps by key before serializing
trimEmptyCollectionsbooleanSerializerSessionOmit empty collections from output
trimEmptyMapsbooleanSerializerSessionOmit empty maps from output
initialDepth / BeanTraverseSession.initialDepthintBeanTraverseSessionInitial depth for indentation
maxIndent / WriterSerializerSession.maxIndentintWriterSerializerSessionMaximum indentation depth for whitespace formatting
quoteChar / WriterSerializerSession.quoteCharcharWriterSerializerSessionQuote character for string values
uriContextUriContextSerializerSessionContext for URI resolution

Parser Session Properties​

These properties apply to all parsers:

PropertyTypeSession ClassDescription
trimStrings / ParserSession.trimStringsbooleanParserSessionTrim whitespace from parsed string values

Format-Specific Session Properties​

JSON / JSON5​

PropertyTypeSession ClassDescription
escapeSolidus / JsonSerializerSession.escapeSolidusbooleanJsonSerializerSessionPrefix / characters with \ escape
validateEnd / JsonParserSession.validateEndbooleanJsonParserSessionValidate that no trailing content follows the parsed value
// Escape forward slashes in URLs
String json = JsonSerializer.DEFAULT
.createSession()
.property("escapeSolidus", true)
.build()
.write("http://example.com");
// Produces: "http:\/\/example.com"

// Require clean end-of-input
JsonParser.DEFAULT
.createSession()
.property("validateEnd", true)
.build()
.read("{\"a\":1}", JsonMap.class); // ok

UON (URL-Encoded Object Notation)​

PropertyTypeSession ClassDescription
encoding / UonSerializerSession.encodingbooleanUonSerializerSessionPercent-encode non-valid URI characters
paramFormat / UonSerializerSession.paramFormatParamFormatUonSerializerSessionFormat for parameter values (UON or PLAINTEXT)
validateEnd / UonParserSession.validateEndbooleanUonParserSessionValidate that no trailing content follows the parsed value
// Use plain-text parameter format (no UON escaping)
String uon = UonSerializer.DEFAULT
.createSession()
.property("paramFormat", ParamFormat.PLAINTEXT)
.build()
.write("hello world");
// Produces: hello world

URL Encoding​

PropertyTypeSession ClassDescription
expandedParams / UrlEncodingSerializerSession.expandedParamsbooleanUrlEncodingSerializerSessionSerialize array/collection bean properties as separate key=value pairs
expandedParams / UrlEncodingParserSession.expandedParamsbooleanUrlEncodingParserSessionParse repeated keys as array/collection values
// Serialize array as repeated parameters: a=1&a=2&a=3
String urlencoded = UrlEncodingSerializer.DEFAULT
.createSession()
.property("expandedParams", true)
.build()
.write(JsonMap.of("a", new int[]{1, 2, 3}));

XML​

PropertyTypeSession ClassDescription
enableNamespaces / XmlSerializerSession.enableNamespacesbooleanXmlSerializerSessionInclude XML namespaces in output
addNamespaceUrisToRoot / XmlSerializerSession.addNamespaceUrisToRootbooleanXmlSerializerSessionAdd xmlns:x attributes to the root element
autoDetectNamespaces / XmlSerializerSession.autoDetectNamespacesbooleanXmlSerializerSessionAuto-detect namespace usage before serializing
defaultNamespace / XmlSerializerSession.defaultNamespaceStringXmlSerializerSessionDefault namespace (e.g. "juneau:http://www.apache.org/juneau/")
textNodeDelimiter / XmlSerializerSession.textNodeDelimiterStringXmlSerializerSessionDelimiter for mixed-content text nodes
preserveRootElement / XmlParserSession.preserveRootElementbooleanXmlParserSessionPreserve the root element name when parsing into a generic JsonMap
validating / XmlParserSession.validatingbooleanXmlParserSessionValidate XML against its schema during parsing
// Parse XML preserving the root element name
JsonMap result = XmlParser.DEFAULT
.createSession()
.property("preserveRootElement", true)
.build()
.read("<root><a>1</a></root>", JsonMap.class);
// result = {"root": {"a": "1"}}

HTML​

PropertyTypeSession ClassDescription
addKeyValueTableHeaders / HtmlSerializerSession.addKeyValueTableHeadersbooleanHtmlSerializerSessionAdd key / value column headers to bean/map tables
detectLinksInStrings / HtmlSerializerSession.detectLinksInStringsbooleanHtmlSerializerSessionAuto-convert URL strings to <a href> anchor tags
detectLabelParameters / HtmlSerializerSession.detectLabelParametersbooleanHtmlSerializerSessionLook for label query parameters in URLs for anchor text
labelParameter / HtmlSerializerSession.labelParameterStringHtmlSerializerSessionQuery parameter name to use as the anchor label (default: "label")
uriAnchorText / HtmlSerializerSession.uriAnchorTextAnchorTextHtmlSerializerSessionStrategy for generating anchor text from URIs
// Use a custom label parameter name
String html = HtmlSerializer.DEFAULT
.createSession()
.property("labelParameter", "title")
.build()
.write("http://example.com?title=My+Page");
// Anchor text will be "My Page"

// Disable auto-link detection
String html2 = HtmlSerializer.DEFAULT
.createSession()
.property("detectLinksInStrings", false)
.build()
.write("http://example.com");
// Produces plain text, not an <a> tag

CSV​

PropertyTypeSession ClassDescription
byteArrayFormat / CsvSerializerSession.byteArrayFormatByteArrayFormatCsvSerializerSessionFormat for byte[] values (e.g. BASE64, HEX, SEMICOLON_DELIMITED)
allowNestedStructures / CsvSerializerSession.allowNestedStructuresbooleanCsvSerializerSessionAllow nested bean structures in CSV output
nullValue / CsvSerializerSession.nullValueStringCsvSerializerSessionString representation for null values (default: <NULL>)
// Use "N/A" for null values in CSV output
String csv = CsvSerializer.DEFAULT
.createSession()
.property("nullValue", "N/A")
.build()
.write(JsonMap.of("name", null, "age", 30));

See also​