Class JsonSerializer
- All Implemented Interfaces:
Function<Object,,String> ThrowingFunction<Object,,String> JsonMetaProvider,ArrayRecordWritable,RecordWritable,TokenWritable
- Direct Known Subclasses:
JcsSerializer,Json5Serializer,JsonlSerializer,JsonSchemaSerializer,JsonSerializer.Readable
Produces strict JSON with double-quoted strings by default. For JSON5-style output (single quotes,
etc.), use Json5Serializer.
Media types
Handles
Produces
Description
The conversion is as follows...
-
Maps (e.g.
HashMaps,TreeMaps) are converted to JSON objects. -
Collections (e.g.
HashSets,LinkedLists) and Java arrays are converted to JSON arrays. -
Stringsare converted to JSON strings. -
Numbers(e.g.Integer,Long,Double) are converted to JSON numbers. -
Booleansare converted to JSON booleans. -
nullsare converted to JSON nulls. -
arraysare converted to JSON arrays. -
beansare converted to JSON objects.
The types above are considered "JSON-primitive" object types.
Any non-JSON-primitive object types are transformed into JSON-primitive object types through
ObjectSwaps associated through the
MarshallingContext.Builder#swaps(Class...) method.
Several default transforms are provided for transforming Dates, Enums, Iterators, etc...
This serializer provides several serialization options. Typically, one of the predefined DEFAULT serializers will be sufficient. However, custom serializers can be constructed to fine-tune behavior.
Behavior-specific subclasses
The following direct subclasses are provided for convenience:
-
Json5Serializer- Default serializer, single quotes, simple mode. -
Json5Serializer.Readable- Default serializer, single quotes, simple mode, with whitespace.
Example:
Example output (Map of name/age):
{
Complex (nested object + array):
{
Notes:
- This class is thread safe and reusable.
See Also:
- JSON
Json5Serializer- For JSON5-style output (single quotes, etc.)
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classJsonSerializer.Builder<SELF extends JsonSerializer.Builder<SELF>>Builder class.static final classstatic classDefault serializer, with whitespace.Nested classes/interfaces inherited from class org.apache.juneau.marshall.serializer.Serializer
Serializer.Null -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected final booleanstatic final JsonSerializerDefault serializer, all default settings.static final JsonSerializerDefault serializer, all default settings.protected final booleanFields inherited from class org.apache.juneau.marshall.serializer.WriterSerializer
maxIndent, quoteChar, quoteCharOverride, useWhitespaceFields inherited from class org.apache.juneau.marshall.serializer.Serializer
accept, addBeanTypes, addRootType, keepNullProperties, listener, nonDefault, produces, sortCollections, sortMaps, trimEmptyCollections, trimEmptyMaps, trimStringsFields inherited from class org.apache.juneau.marshall.MarshallingContextable
marshallingContextFields inherited from class org.apache.juneau.marshall.Context
CONTEXT_APPLY_FILTER -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptioncopy()Creates a builder from this context object.static JsonSerializer.Builder<?>create()Creates a new builder for this object.Create a session builder based on the properties defined on this context.Returns the language-specific metadata on the specified bean property.getJsonClassMeta(ClassMeta<?> cm) Returns the language-specific metadata on the specified class.Returns the schema serializer based on the settings of this serializer.Returns a session to use for this context.protected final booleanAdd"_type" properties when needed.protected final booleanPrefix solidus'/' characters with escapes.Returns the properties on this bean as a map for debugging.writeArrayRecords(Object output) Convenience delegator for the streaming array-elementRecordWriter(uses default session args; seewriteTokens(Object)).writeTokens(Object output) Convenience delegator that opens aJsonTokenWriterover the output using default session arguments (mirrorsSerializer.write(Object, Object)).Methods inherited from class org.apache.juneau.marshall.serializer.WriterSerializer
applyThrows, getMaxIndent, getQuoteChar, getStreamCharset, isUseWhitespace, isWriterSerializer, println, quoteChar, toString, writeMethods inherited from class org.apache.juneau.marshall.serializer.Serializer
createSerializerBuilder, doWrite, forEachAcceptMediaType, getListener, getMediaTypeRanges, getPrimaryMediaType, getResponseContentType, getResponseHeaders, getUriContext, getUriRelativity, getUriResolution, isAddRootType, isKeepNullProperties, isNonDefault, isSortCollections, isSortMaps, isTrimEmptyCollections, isTrimEmptyMaps, isTrimStrings, write, writeToStringMethods inherited from class org.apache.juneau.marshall.MarshallingTraverseContext
getDetectRecursions, getIgnoreRecursions, getInitialDepth, getMaxDepth, isDetectRecursions, isIgnoreRecursions, shouldDetectRecursionsMethods inherited from class org.apache.juneau.marshall.MarshallingContextable
getDurationFormat, getMarshallingContext, getPeriodFormatMethods inherited from class org.apache.juneau.marshall.Context
createBuilder, getAnnotationProvider, init, isDebug, toStringMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface org.apache.juneau.marshall.stream.ArrayRecordWritable
isArrayRecordStreaming, writeArrayRecordsMethods inherited from interface org.apache.juneau.marshall.stream.RecordWritable
isRecordStreamingMethods inherited from interface org.apache.juneau.commons.function.ThrowingFunction
applyMethods inherited from interface org.apache.juneau.marshall.stream.TokenWritable
writeRecords
-
Field Details
-
DEFAULT
Default serializer, all default settings. -
DEFAULT_READABLE
Default serializer, all default settings. -
addBeanTypesJson
-
escapeSolidus
-
-
Constructor Details
-
JsonSerializer
Constructor.- Parameters:
builder- The builder for this object.
-
-
Method Details
-
create
Creates a new builder for this object.- Returns:
- A new builder.
-
copy
Description copied from class:ContextCreates a builder from this context object.Builders are used to define new contexts (e.g. serializers, parsers) based on existing configurations.
- Overrides:
copyin classWriterSerializer- Returns:
- A new Builder object.
-
createSession
Description copied from class:ContextCreate a session builder based on the properties defined on this context.Use this method for creating sessions where you want to override basic settings. Otherwise, use
Context.getSession()directly.- Overrides:
createSessionin classWriterSerializer- Returns:
- A new session builder.
-
getJsonBeanPropertyMeta
Description copied from interface:JsonMetaProviderReturns the language-specific metadata on the specified bean property.- Specified by:
getJsonBeanPropertyMetain interfaceJsonMetaProvider- Parameters:
bpm- The bean property to return the metadata on.- Returns:
- The metadata.
-
getJsonClassMeta
Description copied from interface:JsonMetaProviderReturns the language-specific metadata on the specified class.- Specified by:
getJsonClassMetain interfaceJsonMetaProvider- Parameters:
cm- The class to return the metadata on.- Returns:
- The metadata.
-
getSchemaSerializer
Returns the schema serializer based on the settings of this serializer.Note that this method creates a builder initialized to all default settings, whereas
copy()copies the settings of the object called on.- Returns:
- The schema serializer.
-
getSession
Description copied from class:ContextReturns a session to use for this context.Note that subclasses may opt to return a reusable non-modifiable session.
- Overrides:
getSessionin classWriterSerializer- Returns:
- A new session object.
-
writeTokens
Convenience delegator that opens aJsonTokenWriterover the output using default session arguments (mirrorsSerializer.write(Object, Object)).The real implementation lives on
JsonSerializerSession.writeTokens(Object). Callers that need request-derived configuration should callcreateSession()and invokeJsonSerializerSession.writeTokens(Object)on the built session instead.- Specified by:
writeTokensin interfaceTokenWritable- Parameters:
output- The output. AcceptsWriter,OutputStream,File, orStringBuilder.- Returns:
- A new
JsonTokenWriter. - Throws:
IOException- If the output type is not supported or could not be opened.
-
isAddBeanTypes
Add"_type" properties when needed.- Overrides:
isAddBeanTypesin classSerializer- Returns:
true if"_type" properties will be added to beans if their type cannot be inferred through reflection.- See Also:
-
isEscapeSolidus
Prefix solidus'/' characters with escapes.- Returns:
true if solidus (e.g. slash) characters should be escaped.- See Also:
-
properties
Description copied from class:ContextReturns the properties on this bean as a map for debugging.- Overrides:
propertiesin classWriterSerializer- Returns:
- The properties on this bean as a map for debugging.
-
writeArrayRecords
Convenience delegator for the streaming array-elementRecordWriter(uses default session args; seewriteTokens(Object)). Real impl onJsonSerializerSession.writeArrayRecords(Object).- Specified by:
writeArrayRecordsin interfaceArrayRecordWritable- Parameters:
output- The output.- Returns:
- A new element-streamed
RecordWriter. - Throws:
IOException- If a problem occurred opening the underlying output.
-