Class Serializer.Builder<SELF extends Serializer.Builder<SELF>>

Direct Known Subclasses:
OutputStreamSerializer.Builder, Serializer.DefaultBuilder, WriterSerializer.Builder
Enclosing class:
Serializer

public abstract static class Serializer.Builder<SELF extends Serializer.Builder<SELF>> extends MarshallingTraverseContext.Builder<SELF>
Builder class.
  • Constructor Details

    • Builder

      protected Builder()
      Constructor, default settings.
    • Builder

      protected Builder(Serializer.Builder<?> copyFrom)
      Copy constructor.
      Parameters:
      copyFrom - The builder to copy from.
      Cannot be null.
    • Builder

      protected Builder(Serializer copyFrom)
      Copy constructor.
      Parameters:
      copyFrom - The bean to copy from.
      Cannot be null.
  • Method Details

    • accept

      public SELF accept(String value)
      Specifies the accept media types that the serializer can handle.

      Can contain meta-characters per the media-type specification of RFC2616/14.1

      If 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 be null (will default to the value specified by produces(String)).
      Returns:
      This object.
    • addBeanTypes

      public SELF 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 a Map<String,Object> field where the bean class cannot be determined from the type of the values.

      Note the differences between the following settings:

      Example:

      // Create a serializer that adds _type to nodes. WriterSerializer serializer = JsonSerializer .create() .addBeanTypes() .build(); // Our map of beans to serialize. @Marshalled(typeName="mybean") public class MyBean { public String foo = "bar"; } JsonMap myMap = JsonMap.of("foo", new MyBean()); // Will contain: {"foo":{"_type":"mybean","foo":"bar"}} String json = serializer.write(myMap);

      Token streams: the cursor's raw structural methods do not emit "_type"; however this setting IS honored by TokenWriter.object(Object) when walking a bean.

      Returns:
      This object.
    • addBeanTypes

      public SELF addBeanTypes(boolean value)
      Same as addBeanTypes() but allows you to explicitly specify the value.
      Parameters:
      value - The value for this setting.
      Returns:
      This object.
    • addRootType

      public SELF 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:

      Example:

      // Create a serializer that adds _type to root node. WriterSerializer serializer= JsonSerializer .create() .addRootType() .build(); // Our bean to serialize. @Marshalled(typeName="mybean") public class MyBean { public String foo = "bar"; } // Will contain: {"_type":"mybean","foo":"bar"} String json = serializer.write(new MyBean());

      Token streams: the cursor's raw structural methods do not emit "_type"; however this setting IS honored by TokenWriter.object(Object) for the root value.

      Returns:
      This object.
    • addRootType

      public SELF addRootType(boolean value)
      Same as addRootType() but allows you to explicitly specify the value.
      Parameters:
      value - The value for this setting.
      Returns:
      This object.
    • build

      public Serializer build()
      Description copied from class: Context.Builder
      Build the object.
      Overrides:
      build in class Context.Builder<SELF extends Serializer.Builder<SELF>>
      Returns:
      The built object.
    • copy

      public abstract SELF copy()
      Description copied from class: Context.Builder
      Copy creator.
      Specified by:
      copy in class MarshallingContextable.Builder<SELF extends Serializer.Builder<SELF>>
      Returns:
      A new mutable copy of this builder.
    • getAccept

      public String getAccept()
      Returns the current value for the 'accept' property.
      Returns:
      The current value for the 'accept' property.
    • getProduces

      public String getProduces()
      Returns the current value for the 'produces' property.
      Returns:
      The current value for the 'produces' property.
    • hashKey

      public HashKey hashKey()
      Description copied from class: Context.Builder
      Returns the hashkey of this builder.

      Used to return previously instantiated context beans that have matching hashkeys. The HashKey object is suitable for use as a hashmap key of a map of context beans. A context bean is considered equivalent if the HashKey.equals(Object) method is the same.

      Overrides:
      hashKey in class MarshallingTraverseContext.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 Maps with null values to be lost during parsing.
      Example:

      // Create a serializer that serializes null properties. WriterSerializer serializer = JsonSerializer .create() .keepNullProperties() .build(); // Our bean to serialize. public class MyBean { public String foo = null; } // Will contain "{foo:null}". String json = 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.
    • keepNullProperties

      public SELF keepNullProperties(boolean value)
      Same as keepNullProperties() but allows you to explicitly specify the value.
      Parameters:
      value - The value for this setting.
      Returns:
      This object.
    • nonDefault

      public SELF 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) so 1.0 equals 1, 0.0 equals -0.0, and BigDecimal("1.0") equals BigDecimal("1").

      Precedence: the serialize-side inclusion knobs short-circuit in a fixed order — first "omit" wins:

      1. null values (including Optional.empty()) are governed by keepNullProperties().
      2. Non-null string values are normalized by trimStrings().
      3. Empty collections / arrays / maps are omitted by trimEmptyCollections() / trimEmptyMaps().
      4. Surviving values that equal their type's default are omitted by nonDefault.
      null is resolved by keepNullProperties, not treated as a nonDefault case.
      Example:

      // Create a serializer that omits default-valued properties. WriterSerializer serializer = JsonSerializer .create() .nonDefault() .build(); // Our bean to serialize. public class MyBean { public int count; // Default 0; omitted unless set to non-zero. public String name = "x"; // Bean-default is "x"; only omitted when value equals "x". } // Produces "{}" because both fields equal their defaults. String json = serializer.write(new MyBean());

      See Also:
      Returns:
      This object.
      Since:
      10.0.0
    • nonDefault

      public SELF nonDefault(boolean value)
      Same as nonDefault() but allows you to explicitly specify the value.
      Parameters:
      value - The value for this setting.
      Returns:
      This object.
      Since:
      10.0.0
    • listener

      public SELF listener(Class<? extends SerializerListener> value)
      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 MySerializerListener extends SerializerListener { // A simple property to store our events. public List<String> events = new LinkedList<>(); @Override public <T> void onError(SerializerSession session, Throwable throwable, String msg) { events.add(session.getLastLocation() + "," + msg + "," + throwable); } } // Create a serializer using our listener. WriterSerializer serializer = JsonSerializer .create() .listener(MySerializerListener.class) .build(); // Create a session object. // Needed because listeners are created per-session. try (WriterSerializerSession session = serializer.createSession()) { // Serialize a bean. String json = session.write(new MyBean()); // Get the listener. MySerializerListener listener = 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 be null (no listener will be used, listener methods will not be called).
      Returns:
      This object.
    • produces

      public SELF produces(String value)
      Specifies the media type that this serializer produces.
      Parameters:
      value - The value for this setting.
      Can be null (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. WriterSerializer serializer = JsonSerializer .create() .sortCollections() .build(); // An unsorted array String[] myArray = {"foo","bar","baz"}; // Produces ["bar","baz","foo"] String json = 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 a Collection or array.

      Returns:
      This object.
    • sortCollections

      public SELF sortCollections(boolean value)
      Same as sortCollections() but allows you to explicitly specify the value.
      Parameters:
      value - The value for this setting.
      Returns:
      This object.
    • sortMaps

      public SELF 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. WriterSerializer serializer = JsonSerializer .create() .sortMaps() .build(); // An unsorted map. JsonMap myMap = JsonMap.of("foo",1,"bar",2,"baz",3); // Produces {"bar":2,"baz":3,"foo":1} String json = 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 a Map or bean.

      Returns:
      This object.
    • sortMaps

      public SELF sortMaps(boolean value)
      Same as sortMaps() 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. WriterSerializer serializer = JsonSerializer .create() .trimEmptyCollections() .build(); // A bean with a field with an empty array. public class MyBean { public String[] foo = {}; } // Produces {} String json = 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

      public SELF trimEmptyCollections(boolean value)
      Same as trimEmptyCollections() but allows you to explicitly specify the value.
      Parameters:
      value - The value for this setting.
      Returns:
      This object.
    • trimEmptyMaps

      public SELF 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. WriterSerializer serializer = JsonSerializer .create() .trimEmptyMaps() .build(); // A bean with a field with an empty map. public class MyBean { public JsonMap foo = JsonMap.of(); } // Produces {} String json = 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

      public SELF trimEmptyMaps(boolean value)
      Same as trimEmptyMaps() but allows you to explicitly specify the value.
      Parameters:
      value - The value for this setting.
      Returns:
      This object.
    • trimStrings

      public SELF 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. WriterSerializer serializer = JsonSerializer .create() .trimStrings() .build(); // A map with space-padded keys/values JsonMap myMap = JsonMap.of(" foo ", " bar "); // Produces "{foo:'bar'}" String json = serializer.toString(myMap);

      Returns:
      This object.
    • trimStrings

      public SELF trimStrings(boolean value)
      Same as trimStrings() but allows you to explicitly specify the value.
      Parameters:
      value - The value for this setting.
      Returns:
      This object.
    • uriContext

      public SELF uriContext(UriContext value)
      URI context bean.

      Bean used for resolution of URIs to absolute or root-relative form.

      Example:

      // Our URI contextual information. String authority = "http://localhost:10000"; String contextRoot = "/myContext"; String servletPath = "/myServlet"; String pathInfo = "/foo"; // Create a UriContext object. UriContext uriContext = new UriContext(authority, contextRoot, servletPath, pathInfo); // Associate it with our serializer. WriterSerializer serializer = JsonSerializer .create() .uriContext(uriContext) .uriRelativity(RESOURCE) // Assume relative paths are relative to servlet. .uriResolution(ABSOLUTE) // Serialize URLs as absolute paths. .build(); // A relative URL URL myUrl = new URL("bar"); // Produces "http://localhost:10000/myContext/myServlet/foo/bar" String json = 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 be null (defaults to UriContext.DEFAULT).
      Returns:
      This object.
    • uriRelativity

      URI relativity.

      Defines what relative URIs are relative to when serializing any of the following:

      • URI
      • URL
      • Properties and classes annotated with @Uri

      See uriContext(UriContext) for examples.

      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 is UriRelativity.RESOURCE
      Can be null (defaults to UriRelativity.RESOURCE).
      Returns:
      This object.
    • uriResolution

      URI resolution.

      Defines the resolution level for URIs when serializing any of the following:

      • URI
      • URL
      • Properties and classes annotated with @Uri

      See uriContext(UriContext) for examples.

      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 is UriResolution.NONE
      Can be null (defaults to UriResolution.NONE).
      Returns:
      This object.