Class GsonBuilder
Use this builder to construct a Gson
instance when you need to set configuration
options other than the default. For Gson
with default configuration, it is simpler to
use new Gson()
. GsonBuilder
is best used by creating it, and then invoking its
various configuration methods, and finally calling create.
The following is an example shows how to use the GsonBuilder
to construct a Gson
instance:
Gson gson = new GsonBuilder() .registerTypeAdapter(Id.class, new IdTypeAdapter()) .enableComplexMapKeySerialization() .serializeNulls() .setDateFormat(DateFormat.LONG) .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE) .setPrettyPrinting() .setVersion(1.0) .create();
NOTES:
- the order of invocation of configuration methods does not matter.
- The default serialization of
Date
and its subclasses in Gson does not contain time-zone information. So, if you are using date/time instances, useGsonBuilder
and itssetDateFormat
methods.
- Author:
- Inderjeet Singh, Joel Leitch, Jesse Wilson
-
Constructor Summary
ConstructorsConstructorDescriptionCreates a GsonBuilder instance that can be used to build Gson with various configuration settings. -
Method Summary
Modifier and TypeMethodDescriptionConfigures Gson to apply the passed in exclusion strategy during deserialization.Configures Gson to apply the passed in exclusion strategy during serialization.create()
Creates aGson
instance based on the current configuration.By default, Gson escapes HTML characters such as < > etc.Configures Gson to exclude inner classes during serialization.Enabling this feature will only change the serialized form if the map key is a complex type (i.e.excludeFieldsWithModifiers
(int... modifiers) Configures Gson to excludes all class fields that have the specified modifiers.Configures Gson to exclude all fields from consideration for serialization or deserialization that do not have theExpose
annotation.Makes the output JSON non-executable in Javascript by prefixing the generated JSON with some special text.registerTypeAdapter
(Type type, Object typeAdapter) Configures Gson for custom serialization or deserialization.Register a factory for type adapters.registerTypeHierarchyAdapter
(Class<?> baseType, Object typeAdapter) Configures Gson for custom serialization or deserialization for an inheritance type hierarchy.Configure Gson to serialize null fields.Section 2.4 of JSON specification disallows special double values (NaN, Infinity, -Infinity).setDateFormat
(int style) Configures Gson to to serializeDate
objects according to the style value provided.setDateFormat
(int dateStyle, int timeStyle) Configures Gson to to serializeDate
objects according to the style value provided.setDateFormat
(String pattern) Configures Gson to serializeDate
objects according to the pattern provided.setExclusionStrategies
(ExclusionStrategy... strategies) Configures Gson to apply a set of exclusion strategies during both serialization and deserialization.setFieldNamingPolicy
(FieldNamingPolicy namingConvention) Configures Gson to apply a specific naming policy to an object's field during serialization and deserialization.setFieldNamingStrategy
(FieldNamingStrategy fieldNamingStrategy) Configures Gson to apply a specific naming policy strategy to an object's field during serialization and deserialization.By default, Gson is strict and only accepts JSON as specified by RFC 4627.setLongSerializationPolicy
(LongSerializationPolicy serializationPolicy) Configures Gson to apply a specific serialization policy forLong
andlong
objects.setNumberToNumberStrategy
(ToNumberStrategy numberToNumberStrategy) Configures Gson to apply a specific number strategy during deserialization ofNumber
.setObjectToNumberStrategy
(ToNumberStrategy objectToNumberStrategy) Configures Gson to apply a specific number strategy during deserialization ofObject
.Configures Gson to output Json that fits in a page for pretty printing.setVersion
(double ignoreVersionsAfter) Configures Gson to enable versioning support.
-
Constructor Details
-
GsonBuilder
public GsonBuilder()Creates a GsonBuilder instance that can be used to build Gson with various configuration settings. GsonBuilder follows the builder pattern, and it is typically used by first invoking various configuration methods to set desired options, and finally callingcreate()
.
-
-
Method Details
-
setVersion
Configures Gson to enable versioning support.- Parameters:
ignoreVersionsAfter
- any field or type marked with a version higher than this value are ignored during serialization or deserialization.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern
-
excludeFieldsWithModifiers
Configures Gson to excludes all class fields that have the specified modifiers. By default, Gson will exclude all fields marked transient or static. This method will override that behavior.- Parameters:
modifiers
- the field modifiers. You must use the modifiers specified in theModifier
class. For example,Modifier.TRANSIENT
,Modifier.STATIC
.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern
-
generateNonExecutableJson
Makes the output JSON non-executable in Javascript by prefixing the generated JSON with some special text. This prevents attacks from third-party sites through script sourcing. See Gson Issue 42 for details.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - Since:
- 1.3
-
excludeFieldsWithoutExposeAnnotation
Configures Gson to exclude all fields from consideration for serialization or deserialization that do not have theExpose
annotation.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern
-
serializeNulls
Configure Gson to serialize null fields. By default, Gson omits all fields that are null during serialization.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - Since:
- 1.2
-
enableComplexMapKeySerialization
Enabling this feature will only change the serialized form if the map key is a complex type (i.e. non-primitive) in its serialized JSON form. The default implementation of map serialization usestoString()
on the key; however, when this is called then one of the following cases apply:Maps as JSON objects
For this case, assume that a type adapter is registered to serialize and deserialize somePoint
class, which contains an x and y coordinate, to/from the JSON Primitive string value"(x,y)"
. The Java map would then be serialized as aJsonObject
.Below is an example:
Gson gson = new GsonBuilder() .register(Point.class, new MyPointTypeAdapter()) .enableComplexMapKeySerialization() .create(); Map<Point, String> original = new LinkedHashMap<Point, String>(); original.put(new Point(5, 6), "a"); original.put(new Point(8, 8), "b"); System.out.println(gson.toJson(original, type));
{ "(5,6)": "a", "(8,8)": "b" }
Maps as JSON arrays
For this case, assume that a type adapter was NOT registered for somePoint
class, but rather the default Gson serialization is applied. In this case, somenew Point(2,3)
would serialize as{"x":2,"y":5}
.Given the assumption above, a
Map<Point, String>
will be serialize as an array of arrays (can be viewed as an entry set of pairs).Below is an example of serializing complex types as JSON arrays:
Gson gson = new GsonBuilder() .enableComplexMapKeySerialization() .create(); Map<Point, String> original = new LinkedHashMap<Point, String>(); original.put(new Point(5, 6), "a"); original.put(new Point(8, 8), "b"); System.out.println(gson.toJson(original, type));
The JSON output would look as follows:[ [ { "x": 5, "y": 6 }, "a" ], [ { "x": 8, "y": 8 }, "b" ] ]
- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - Since:
- 1.7
-
disableInnerClassSerialization
Configures Gson to exclude inner classes during serialization.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - Since:
- 1.3
-
setLongSerializationPolicy
Configures Gson to apply a specific serialization policy forLong
andlong
objects.- Parameters:
serializationPolicy
- the particular policy to use for serializing longs.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - Since:
- 1.3
-
setFieldNamingPolicy
Configures Gson to apply a specific naming policy to an object's field during serialization and deserialization.- Parameters:
namingConvention
- the JSON field naming convention to use for serialization and deserialization.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern
-
setFieldNamingStrategy
Configures Gson to apply a specific naming policy strategy to an object's field during serialization and deserialization.- Parameters:
fieldNamingStrategy
- the actual naming strategy to apply to the fields- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - Since:
- 1.3
-
setObjectToNumberStrategy
Configures Gson to apply a specific number strategy during deserialization ofObject
.- Parameters:
objectToNumberStrategy
- the actual object-to-number strategy- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - See Also:
-
setNumberToNumberStrategy
Configures Gson to apply a specific number strategy during deserialization ofNumber
.- Parameters:
numberToNumberStrategy
- the actual number-to-number strategy- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - See Also:
-
setExclusionStrategies
Configures Gson to apply a set of exclusion strategies during both serialization and deserialization. Each of thestrategies
will be applied as a disjunction rule. This means that if one of thestrategies
suggests that a field (or class) should be skipped then that field (or object) is skipped during serialization/deserialization.- Parameters:
strategies
- the set of strategy object to apply during object (de)serialization.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - Since:
- 1.4
-
addSerializationExclusionStrategy
Configures Gson to apply the passed in exclusion strategy during serialization. If this method is invoked numerous times with different exclusion strategy objects then the exclusion strategies that were added will be applied as a disjunction rule. This means that if one of the added exclusion strategies suggests that a field (or class) should be skipped then that field (or object) is skipped during its serialization.- Parameters:
strategy
- an exclusion strategy to apply during serialization.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - Since:
- 1.7
-
addDeserializationExclusionStrategy
Configures Gson to apply the passed in exclusion strategy during deserialization. If this method is invoked numerous times with different exclusion strategy objects then the exclusion strategies that were added will be applied as a disjunction rule. This means that if one of the added exclusion strategies suggests that a field (or class) should be skipped then that field (or object) is skipped during its deserialization.- Parameters:
strategy
- an exclusion strategy to apply during deserialization.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - Since:
- 1.7
-
setPrettyPrinting
Configures Gson to output Json that fits in a page for pretty printing. This option only affects Json serialization.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern
-
setLenient
By default, Gson is strict and only accepts JSON as specified by RFC 4627. This option makes the parser liberal in what it accepts.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - See Also:
-
disableHtmlEscaping
By default, Gson escapes HTML characters such as < > etc. Use this option to configure Gson to pass-through HTML characters as is.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - Since:
- 1.3
-
setDateFormat
Configures Gson to serializeDate
objects according to the pattern provided. You can call this method orsetDateFormat(int)
multiple times, but only the last invocation will be used to decide the serialization format.The date format will be used to serialize and deserialize
Date
and in case thejava.sql
module is present, alsoTimestamp
andDate
.Note that this pattern must abide by the convention provided by
SimpleDateFormat
class. See the documentation inSimpleDateFormat
for more information on valid date and time patterns.- Parameters:
pattern
- the pattern that dates will be serialized/deserialized to/from- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - Since:
- 1.2
-
setDateFormat
Configures Gson to to serializeDate
objects according to the style value provided. You can call this method orsetDateFormat(String)
multiple times, but only the last invocation will be used to decide the serialization format.Note that this style value should be one of the predefined constants in the
DateFormat
class. See the documentation inDateFormat
for more information on the valid style constants.- Parameters:
style
- the predefined date style that date objects will be serialized/deserialized to/from- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - Since:
- 1.2
-
setDateFormat
Configures Gson to to serializeDate
objects according to the style value provided. You can call this method orsetDateFormat(String)
multiple times, but only the last invocation will be used to decide the serialization format.Note that this style value should be one of the predefined constants in the
DateFormat
class. See the documentation inDateFormat
for more information on the valid style constants.- Parameters:
dateStyle
- the predefined date style that date objects will be serialized/deserialized to/fromtimeStyle
- the predefined style for the time portion of the date objects- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - Since:
- 1.2
-
registerTypeAdapter
Configures Gson for custom serialization or deserialization. This method combines the registration of anTypeAdapter
,InstanceCreator
,JsonSerializer
, and aJsonDeserializer
. It is best used when a single objecttypeAdapter
implements all the required interfaces for custom serialization with Gson. If a type adapter was previously registered for the specifiedtype
, it is overwritten.This registers the type specified and no other types: you must manually register related types! For example, applications registering
boolean.class
should also registerBoolean.class
.- Parameters:
type
- the type definition for the type adapter being registeredtypeAdapter
- This object must implement at least one of theTypeAdapter
,InstanceCreator
,JsonSerializer
, and aJsonDeserializer
interfaces.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern
-
registerTypeAdapterFactory
Register a factory for type adapters. Registering a factory is useful when the type adapter needs to be configured based on the type of the field being processed. Gson is designed to handle a large number of factories, so you should consider registering them to be at par with registering an individual type adapter.- Since:
- 2.1
-
registerTypeHierarchyAdapter
Configures Gson for custom serialization or deserialization for an inheritance type hierarchy. This method combines the registration of aTypeAdapter
,JsonSerializer
and aJsonDeserializer
. If a type adapter was previously registered for the specified type hierarchy, it is overridden. If a type adapter is registered for a specific type in the type hierarchy, it will be invoked instead of the one registered for the type hierarchy.- Parameters:
baseType
- the class definition for the type adapter being registered for the base class or interfacetypeAdapter
- This object must implement at least one ofTypeAdapter
,JsonSerializer
orJsonDeserializer
interfaces.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - Since:
- 1.7
-
serializeSpecialFloatingPointValues
Section 2.4 of JSON specification disallows special double values (NaN, Infinity, -Infinity). However, Javascript specification (see section 4.3.20, 4.3.22, 4.3.23) allows these values as valid Javascript values. Moreover, most JavaScript engines will accept these special values in JSON without problem. So, at a practical level, it makes sense to accept these values as valid JSON even though JSON specification disallows them.Gson always accepts these special values during deserialization. However, it outputs strictly compliant JSON. Hence, if it encounters a float value
Float.NaN
,Float.POSITIVE_INFINITY
,Float.NEGATIVE_INFINITY
, or a double valueDouble.NaN
,Double.POSITIVE_INFINITY
,Double.NEGATIVE_INFINITY
, it will throw anIllegalArgumentException
. This method provides a way to override the default behavior when you know that the JSON receiver will be able to handle these special values.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - Since:
- 1.3
-
create
Creates aGson
instance based on the current configuration. This method is free of side-effects to thisGsonBuilder
instance and hence can be called multiple times.- Returns:
- an instance of Gson configured with the options currently set in this builder
-