Class Serializer.Builder<SELF extends Serializer.Builder<SELF>>
- Direct Known Subclasses:
OutputStreamSerializer.Builder,Serializer.DefaultBuilder,WriterSerializer.Builder
- Enclosing class:
- Serializer
-
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedBuilder()Constructor, default settings.protectedBuilder(Serializer copyFrom) Copy constructor.protectedBuilder(Serializer.Builder<?> copyFrom) Copy constructor. -
Method Summary
Modifier and TypeMethodDescriptionSpecifies the accept media types that the serializer can handle.Add"_type" properties when needed.addBeanTypes(boolean value) Same asaddBeanTypes()but allows you to explicitly specify the value.Add type attribute to root nodes.addRootType(boolean value) Same asaddRootType()but allows you to explicitly specify the value.build()Build the object.abstract SELFcopy()Copy creator.Returns the current value for the 'accept' property.Returns the current value for the 'produces' property.hashKey()Returns the hashkey of this builder.Don't trim null bean property values.keepNullProperties(boolean value) Same askeepNullProperties()but allows you to explicitly specify the value.listener(Class<? extends SerializerListener> value) Serializer listener.Don't serialize bean properties whose values equal the default for their type.nonDefault(boolean value) Same asnonDefault()but allows you to explicitly specify the value.Specifies the media type that this serializer produces.Sort arrays and collections alphabetically.sortCollections(boolean value) Same assortCollections()but allows you to explicitly specify the value.sortMaps()Sort maps alphabetically.sortMaps(boolean value) Same assortMaps()but allows you to explicitly specify the value.Trim empty lists and arrays.trimEmptyCollections(boolean value) Same astrimEmptyCollections()but allows you to explicitly specify the value.Trim empty maps.trimEmptyMaps(boolean value) Same astrimEmptyMaps()but allows you to explicitly specify the value.Trim strings.trimStrings(boolean value) Same astrimStrings()but allows you to explicitly specify the value.uriContext(UriContext value) URI context bean.uriRelativity(UriRelativity value) URI relativity.uriResolution(UriResolution value) URI resolution.Methods inherited from class org.apache.juneau.marshall.MarshallingTraverseContext.Builder
detectRecursions, detectRecursions, ignoreRecursions, ignoreRecursions, initialDepth, maxDepthMethods inherited from class org.apache.juneau.marshall.MarshallingContextable.Builder
activeView, annotations, beanClassVisibility, beanConstructorVisibility, beanDictionary, beanFieldVisibility, beanInterceptor, beanMapPutReturnsOldValue, beanMethodVisibility, beanProperties, beanProperties, beanProperties, beanPropertiesExcludes, beanPropertiesExcludes, beanPropertiesExcludes, beanPropertiesReadOnly, beanPropertiesReadOnly, beanPropertiesReadOnly, beanPropertiesWriteOnly, beanPropertiesWriteOnly, beanPropertiesWriteOnly, beansRequireDefaultConstructor, beansRequireSerializable, beansRequireSettersForGetters, bigNumberFormat, binaryFormat, bitSetFormat, booleanFormat, calendarFormat, classFormat, classLoader, currencyFormat, dateFormat, debug, dictionaryOn, disableBeansRequireSomeProperties, disableDefaultViewInclusion, disableIgnoreMissingSetters, disableIgnoreTransientFields, disableIgnoreUnknownNullBeanProperties, disableInterfaceProxies, durationFormat, enumFormat, example, example, findFluentSetters, findFluentSetters, floatFormat, ignoreInvocationExceptionsOnGetters, ignoreInvocationExceptionsOnSetters, ignoreUnknownBeanProperties, ignoreUnknownEnumValues, implClass, implClasses, interfaceClass, interfaces, locale, localeFormat, marshallingContext, marshallingContext, marshallingContext, marshallingContext, mediaType, notBeanClasses, notBeanPackages, periodFormat, propertyNamer, propertyNamer, recordComponentOrder, stopClass, swap, swap, swaps, swaps, temporalFormat, timeZone, timeZoneFormat, typeName, typePropertyName, typePropertyName, unsortedProperties, unsortedProperties, useJavaBeanIntrospector, uuidFormat, validateSchema, validateSchemaMethods inherited from class org.apache.juneau.marshall.Context.Builder
annotations, apply, applyAnnotations, applyAnnotations, asSubtype, build, cache, canApply, copyOrNull, debug, getApplied, getType, impl, isDebug, registerBuilders, self, type
-
Constructor Details
-
Builder
protected Builder()Constructor, default settings. -
Builder
Copy constructor.- Parameters:
copyFrom- The builder to copy from.
Cannot benull .
-
Builder
Copy constructor.- Parameters:
copyFrom- The bean to copy from.
Cannot benull .
-
-
Method Details
-
accept
Specifies the accept media types that the serializer can handle.Can contain meta-characters per the
media-type specification of RFC2616/14.1If empty, then assumes the only media type supported is
produces .For example, if this serializer produces
"application/json" but should handle media types of"application/json" and"text/json" , then the arguments should be:builder .produces("application/json" );builder .accept("application/json,text/json" );The accept value can also contain q-values.
- Parameters:
value- The value for this setting.
Can benull (will default to the value specified byproduces(String)).- Returns:
- This object.
-
addBeanTypes
Add"_type" properties when needed.When enabled,
"_type" properties will be added to beans if their type cannot be inferred through reflection.This is used to recreate the correct objects during parsing if the object types cannot be inferred.
For example, when serializing aMap<String,Object> field where the bean class cannot be determined from the type of the values.Note the differences between the following settings:
addRootType()- Affects whether'_type' is added to root node.addBeanTypes()- Affects whether'_type' is added to any nodes.
Example:
// Create a serializer that adds _type to nodes. WriterSerializerserializer = JsonSerializer .create () .addBeanTypes() .build();// Our map of beans to serialize. @Marshalled (typeName="mybean" )public class MyBean {public Stringfoo ="bar" ; } JsonMapmyMap = JsonMap.of("foo" ,new MyBean());// Will contain: {"foo":{"_type":"mybean","foo":"bar"}} Stringjson =serializer .write(myMap );Token streams: the cursor's raw structural methods do not emit
"_type" ; however this setting IS honored byTokenWriter.object(Object)when walking a bean.- Returns:
- This object.
-
addBeanTypes
Same asaddBeanTypes()but allows you to explicitly specify the value.- Parameters:
value- The value for this setting.- Returns:
- This object.
-
addRootType
Add type attribute to root nodes.When enabled,
"_type" properties will be added to top-level beans.When disabled, it is assumed that the parser knows the exact Java POJO type being parsed, and therefore top-level type information that might normally be included to determine the data type will not be serialized.
For example, when serializing a top-level POJO with a
@Marshalled(typeName)value, a'_type' attribute will only be added when this setting is enabled.Note the differences between the following settings:
addRootType()- Affects whether'_type' is added to root node.addBeanTypes()- Affects whether'_type' is added to any nodes.
Example:
// Create a serializer that adds _type to root node. WriterSerializerserializer = JsonSerializer .create () .addRootType() .build();// Our bean to serialize. @Marshalled (typeName="mybean" )public class MyBean {public Stringfoo ="bar" ; }// Will contain: {"_type":"mybean","foo":"bar"} Stringjson =serializer .write(new MyBean());Token streams: the cursor's raw structural methods do not emit
"_type" ; however this setting IS honored byTokenWriter.object(Object)for the root value.- Returns:
- This object.
-
addRootType
Same asaddRootType()but allows you to explicitly specify the value.- Parameters:
value- The value for this setting.- Returns:
- This object.
-
build
Description copied from class:Context.BuilderBuild the object.- Overrides:
buildin classContext.Builder<SELF extends Serializer.Builder<SELF>>- Returns:
- The built object.
-
copy
Description copied from class:Context.BuilderCopy creator.- Specified by:
copyin classMarshallingContextable.Builder<SELF extends Serializer.Builder<SELF>>- Returns:
- A new mutable copy of this builder.
-
getAccept
Returns the current value for the 'accept' property.- Returns:
- The current value for the 'accept' property.
-
getProduces
Returns the current value for the 'produces' property.- Returns:
- The current value for the 'produces' property.
-
hashKey
Description copied from class:Context.BuilderReturns the hashkey of this builder.Used to return previously instantiated context beans that have matching hashkeys. The
HashKeyobject is suitable for use as a hashmap key of a map of context beans. A context bean is considered equivalent if theHashKey.equals(Object)method is the same.- Overrides:
hashKeyin classMarshallingTraverseContext.Builder<SELF extends Serializer.Builder<SELF>>- Returns:
- The hashkey of this builder.
-
keepNullProperties
Don't trim null bean property values.When enabled, null bean values will be serialized to the output.
Notes:
- Not enabling this setting will cause
Map s withnull values to be lost during parsing.
Example:
// Create a serializer that serializes null properties. WriterSerializerserializer = JsonSerializer .create () .keepNullProperties() .build();// Our bean to serialize. public class MyBean {public Stringfoo =null ; }// Will contain "{foo:null}". Stringjson =serializer .write(new MyBean());Token streams: the cursor's raw structural methods always emit what the caller asks for; however this setting IS honored by
TokenWriter.object(Object)during a bean walk.- Returns:
- This object.
- Not enabling this setting will cause
-
keepNullProperties
Same askeepNullProperties()but allows you to explicitly specify the value.- Parameters:
value- The value for this setting.- Returns:
- This object.
-
nonDefault
Don't serialize bean properties whose values equal the default for their type.When enabled, bean properties whose current value equals the type's natural default are omitted from the serialized output. This is the Juneau analog of Jackson's
JsonInclude.Include.NON_DEFAULT inclusion mode.The notion of "default" depends on the property type:
- Primitives and primitive wrappers (
,int Integer,,boolean Boolean, etc.) use the Java type default (0 ,false ,'\0',null ). - Bean properties on bean-typed property values use a reference instance of the bean type —
instantiated once via the no-arg constructor and cached on the
ClassMeta— and the property is omitted when its current value equals that reference's value. - When no reference instance can be built (no accessible no-arg constructor, or instantiation
throws),
nonDefault is silently skipped for that bean — the property is emitted normally rather than failing the serialize.
Equality semantics: value-equals-default uses
Objects.equals(java.lang.Object, java.lang.Object), with numeric values compared by mathematical value (BigDecimal.compareTo-style) so1.0 equals1 ,0.0 equals-0.0 , andBigDecimal(equals"1.0" )BigDecimal(."1" )Precedence: the serialize-side inclusion knobs short-circuit in a fixed order — first "omit" wins:
null values (includingOptional.empty()) are governed bykeepNullProperties().- Non-
null string values are normalized bytrimStrings(). - Empty collections / arrays / maps are omitted by
trimEmptyCollections()/trimEmptyMaps(). - Surviving values that equal their type's default are omitted by
nonDefault .
null is resolved bykeepNullProperties , not treated as anonDefault case.Example:
// Create a serializer that omits default-valued properties. WriterSerializerserializer = JsonSerializer .create () .nonDefault() .build();// Our bean to serialize. public class MyBean {public int count ;// Default 0; omitted unless set to non-zero. public Stringname ="x" ;// Bean-default is "x"; only omitted when value equals "x". }// Produces "{}" because both fields equal their defaults. Stringjson =serializer .write(new MyBean());See Also:
- Returns:
- This object.
- Since:
- 10.0.0
- Primitives and primitive wrappers (
-
nonDefault
Same asnonDefault()but allows you to explicitly specify the value.- Parameters:
value- The value for this setting.- Returns:
- This object.
- Since:
- 10.0.0
-
listener
Serializer listener.Class used to listen for errors and warnings that occur during serialization.
Example:
// Define our serializer listener. // Simply captures all errors. public class MySerializerListenerextends SerializerListener {// A simple property to store our events. public List<String>events =new LinkedList<>();@Override public <T>void onError(SerializerSessionsession , Throwablethrowable , Stringmsg ) {events .add(session .getLastLocation() +"," +msg +"," +throwable ); } }// Create a serializer using our listener. WriterSerializerserializer = JsonSerializer .create () .listener(MySerializerListener.class ) .build();// Create a session object. // Needed because listeners are created per-session. try (WriterSerializerSessionsession =serializer .createSession()) {// Serialize a bean. Stringjson =session .write(new MyBean());// Get the listener. MySerializerListenerlistener =session .getListener(MySerializerListener.class );// Dump the results to the console. Json5.DEFAULT .println(listener .events ); }Token streams: this setting is not honored by
writeTokens— listeners are POJO-level observers with no token-layer analog.- Parameters:
value- The new value for this property.
Can benull (no listener will be used, listener methods will not be called).- Returns:
- This object.
-
produces
Specifies the media type that this serializer produces.- Parameters:
value- The value for this setting.
Can benull (clears the produces media type).- Returns:
- This object.
-
sortCollections
Sort arrays and collections alphabetically.When enabled, copies and sorts the contents of arrays and collections before serializing them.
Note that this introduces a performance penalty since it requires copying the existing collection.
Example:
// Create a serializer that sorts arrays and collections before serialization. WriterSerializerserializer = JsonSerializer .create () .sortCollections() .build();// An unsorted array String[]myArray = {"foo" ,"bar" ,"baz" };// Produces ["bar","baz","foo"] Stringjson =serializer .write(myArray );Token streams: the cursor's raw structural methods emit elements in the order the caller emits them. This setting IS honored by
TokenWriter.object(Object)when walking aCollectionor array.- Returns:
- This object.
-
sortCollections
Same assortCollections()but allows you to explicitly specify the value.- Parameters:
value- The value for this setting.- Returns:
- This object.
-
sortMaps
Sort maps alphabetically.When enabled, copies and sorts the contents of maps by their keys before serializing them.
Note that this introduces a performance penalty.
Example:
// Create a serializer that sorts maps before serialization. WriterSerializerserializer = JsonSerializer .create () .sortMaps() .build();// An unsorted map. JsonMapmyMap = JsonMap.of ("foo" ,1,"bar" ,2,"baz" ,3);// Produces {"bar":2,"baz":3,"foo":1} Stringjson =serializer .write(myMap );Token streams: the cursor's raw structural methods emit map / bean entries in the order the caller emits them. This setting IS honored by
TokenWriter.object(Object)when walking aMapor bean.- Returns:
- This object.
-
sortMaps
Same assortMaps()but allows you to explicitly specify the value.- Parameters:
value- The value for this setting.- Returns:
- This object.
-
trimEmptyCollections
Trim empty lists and arrays.When enabled, empty lists and arrays will not be serialized.
Note that enabling this setting has the following effects on parsing:
- Map entries with empty list values will be lost.
- Bean properties with empty list values will not be set.
Example:
// Create a serializer that skips empty arrays and collections. WriterSerializerserializer = JsonSerializer .create () .trimEmptyCollections() .build();// A bean with a field with an empty array. public class MyBean {public String[]foo = {}; }// Produces {} Stringjson =serializer .write(new MyBean());Token streams: the cursor's raw structural methods emit what the caller asks for. This setting IS honored by
TokenWriter.object(Object)during a bean walk — bean / map fields whose value is an empty collection or array are skipped.- Returns:
- This object.
-
trimEmptyCollections
Same astrimEmptyCollections()but allows you to explicitly specify the value.- Parameters:
value- The value for this setting.- Returns:
- This object.
-
trimEmptyMaps
Trim empty maps.When enabled, empty map values will not be serialized to the output.
Note that enabling this setting has the following effects on parsing:
- Bean properties with empty map values will not be set.
Example:
// Create a serializer that skips empty maps. WriterSerializerserializer = JsonSerializer .create () .trimEmptyMaps() .build();// A bean with a field with an empty map. public class MyBean {public JsonMapfoo = JsonMap.of (); }// Produces {} Stringjson =serializer .write(new MyBean());Token streams: the cursor's raw structural methods emit what the caller asks for. This setting IS honored by
TokenWriter.object(Object)during a bean walk — bean / map fields whose value is an empty map are skipped.- Returns:
- This object.
-
trimEmptyMaps
Same astrimEmptyMaps()but allows you to explicitly specify the value.- Parameters:
value- The value for this setting.- Returns:
- This object.
-
trimStrings
Trim strings.When enabled, string values will be trimmed of whitespace using
String.trim()before being serialized.Example:
// Create a serializer that trims strings before serialization. WriterSerializerserializer = JsonSerializer .create () .trimStrings() .build();// A map with space-padded keys/values JsonMapmyMap = JsonMap.of (" foo " ," bar " );// Produces "{foo:'bar'}" Stringjson =serializer .toString(myMap );- Returns:
- This object.
-
trimStrings
Same astrimStrings()but allows you to explicitly specify the value.- Parameters:
value- The value for this setting.- Returns:
- This object.
-
uriContext
URI context bean.Bean used for resolution of URIs to absolute or root-relative form.
Example:
// Our URI contextual information. Stringauthority ="http://localhost:10000" ; StringcontextRoot ="/myContext" ; StringservletPath ="/myServlet" ; StringpathInfo ="/foo" ;// Create a UriContext object. UriContexturiContext =new UriContext(authority ,contextRoot ,servletPath ,pathInfo );// Associate it with our serializer. WriterSerializerserializer = JsonSerializer .create () .uriContext(uriContext ) .uriRelativity(RESOURCE )// Assume relative paths are relative to servlet. .uriResolution(ABSOLUTE )// Serialize URLs as absolute paths. .build();// A relative URL URLmyUrl =new URL("bar" );// Produces "http://localhost:10000/myContext/myServlet/foo/bar" Stringjson =serializer .toString(myUrl );See Also:
Token streams: this setting is not honored by
writeTokens— URI rewriting is a databind concern; the token layer emits string values verbatim.- Parameters:
value- The new value for this property.
Can benull (defaults toUriContext.DEFAULT ).- Returns:
- This object.
-
uriRelativity
URI relativity.Defines what relative URIs are relative to when serializing any of the following:
See
uriContext(UriContext)for examples.UriRelativity.RESOURCE- Relative URIs should be considered relative to the servlet URI.UriRelativity.PATH_INFO- Relative URIs should be considered relative to the request URI.
See Also:
Token streams: this setting is not honored by
writeTokens— URI rewriting is a databind concern.- Parameters:
value- The new value for this property.
The default isUriRelativity.RESOURCE
Can benull (defaults toUriRelativity.RESOURCE ).- Returns:
- This object.
-
uriResolution
URI resolution.Defines the resolution level for URIs when serializing any of the following:
See
uriContext(UriContext)for examples.UriResolution.ABSOLUTE- Resolve to an absolute URL (e.g."http://host:port/context-root/servlet-path/path-info" ).UriResolution.ROOT_RELATIVE- Resolve to a root-relative URL (e.g."/context-root/servlet-path/path-info" ).UriResolution.NONE- Don't do any URL resolution.
See Also:
Token streams: this setting is not honored by
writeTokens— URI rewriting is a databind concern.- Parameters:
value- The new value for this property.
The default isUriResolution.NONE
Can benull (defaults toUriResolution.NONE ).- Returns:
- This object.
-