- java.lang.Object
-
- com.google.gson.GsonBuilder
-
public final class GsonBuilder extends Object
Use this builder to construct aGson
instance when you need to set configuration options other than the default. ForGson
with default configuration, it is simpler to usenew Gson()
.GsonBuilder
is best used by creating it, and then invoking its various configuration methods, and finally calling create.The following 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, 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. - By default no explicit
Strictness
is set; some of theGson
methods behave as ifStrictness.LEGACY_STRICT
was used whereas others behave as ifStrictness.LENIENT
was used. Prefer explicitly setting a strictness withsetStrictness(Strictness)
to avoid this legacy behavior.
- Author:
- Inderjeet Singh, Joel Leitch, Jesse Wilson
-
-
Constructor Summary
Constructors Constructor Description GsonBuilder()
Creates a GsonBuilder instance that can be used to build Gson with various configuration settings.
-
Method Summary
All Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description GsonBuilder
addDeserializationExclusionStrategy(ExclusionStrategy strategy)
Configures Gson to apply the passed in exclusion strategy during deserialization.GsonBuilder
addReflectionAccessFilter(ReflectionAccessFilter filter)
Adds a reflection access filter.GsonBuilder
addSerializationExclusionStrategy(ExclusionStrategy strategy)
Configures Gson to apply the passed in exclusion strategy during serialization.Gson
create()
Creates aGson
instance based on the current configuration.GsonBuilder
disableHtmlEscaping()
By default, Gson escapes HTML characters such as < > etc.GsonBuilder
disableInnerClassSerialization()
Configures Gson to exclude inner classes (= non-static
nested classes) during serialization and deserialization.GsonBuilder
disableJdkUnsafe()
Disables usage of JDK'ssun.misc.Unsafe
.GsonBuilder
enableComplexMapKeySerialization()
Configures Gson to serializeMap
objects with complex keys as JSON arrays.GsonBuilder
excludeFieldsWithModifiers(int... modifiers)
Configures Gson to excludes all class fields that have the specified modifiers.GsonBuilder
excludeFieldsWithoutExposeAnnotation()
Configures Gson to exclude all fields from consideration for serialization and deserialization that do not have theExpose
annotation.GsonBuilder
generateNonExecutableJson()
Makes the output JSON non-executable in Javascript by prefixing the generated JSON with some special text.GsonBuilder
registerTypeAdapter(Type type, Object typeAdapter)
Configures Gson for custom serialization or deserialization.GsonBuilder
registerTypeAdapterFactory(TypeAdapterFactory factory)
Registers a factory for type adapters.GsonBuilder
registerTypeHierarchyAdapter(Class<?> baseType, Object typeAdapter)
Configures Gson for custom serialization or deserialization for an inheritance type hierarchy.GsonBuilder
serializeNulls()
Configures Gson to serialize null fields.GsonBuilder
serializeSpecialFloatingPointValues()
Section 6 of JSON specification disallows special double values (NaN, Infinity, -Infinity).GsonBuilder
setDateFormat(int dateStyle)
Deprecated.Counterintuitively, despite this method taking only a 'date style' Gson will use a format which includes both date and time, with the 'time style' being the last value set bysetDateFormat(int, int)
.GsonBuilder
setDateFormat(int dateStyle, int timeStyle)
Configures Gson to serializeDate
objects according to the style value provided.GsonBuilder
setDateFormat(String pattern)
Configures Gson to serializeDate
objects according to the pattern provided.GsonBuilder
setExclusionStrategies(ExclusionStrategy... strategies)
Configures Gson to apply a set of exclusion strategies during both serialization and deserialization.GsonBuilder
setFieldNamingPolicy(FieldNamingPolicy namingConvention)
Configures Gson to apply a specific naming policy to an object's fields during serialization and deserialization.GsonBuilder
setFieldNamingStrategy(FieldNamingStrategy fieldNamingStrategy)
Configures Gson to apply a specific naming strategy to an object's fields during serialization and deserialization.GsonBuilder
setFormattingStyle(FormattingStyle formattingStyle)
Configures Gson to output JSON that uses a certain kind of formatting style (for example newline and indent).GsonBuilder
setLenient()
Deprecated.This method is equivalent to callingsetStrictness(Strictness)
withStrictness.LENIENT
:setStrictness(Strictness.LENIENT)
GsonBuilder
setLongSerializationPolicy(LongSerializationPolicy serializationPolicy)
Configures Gson to apply a specific serialization policy forLong
andlong
objects.GsonBuilder
setNumberToNumberStrategy(ToNumberStrategy numberToNumberStrategy)
Configures Gson to apply a specific number strategy during deserialization ofNumber
.GsonBuilder
setObjectToNumberStrategy(ToNumberStrategy objectToNumberStrategy)
Configures Gson to apply a specific number strategy during deserialization ofObject
.GsonBuilder
setPrettyPrinting()
Configures Gson to output JSON that fits in a page for pretty printing.GsonBuilder
setStrictness(Strictness strictness)
Sets the strictness of this builder to the provided parameter.GsonBuilder
setVersion(double version)
Configures Gson to enable versioning support.
-
-
-
Constructor Detail
-
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 Detail
-
setVersion
@CanIgnoreReturnValue public GsonBuilder setVersion(double version)
Configures Gson to enable versioning support. Versioning support works based on the annotation typesSince
andUntil
. It allows including or excluding fields and classes based on the specified version. See the documentation of these annotation types for more information.By default versioning support is disabled and usage of
@Since
and@Until
has no effect.- Parameters:
version
- the version number to use.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - Throws:
IllegalArgumentException
- if the version number is NaN or negative- See Also:
Since
,Until
-
excludeFieldsWithModifiers
@CanIgnoreReturnValue public GsonBuilder excludeFieldsWithModifiers(int... modifiers)
Configures Gson to excludes all class fields that have the specified modifiers. By default, Gson will exclude all fields markedtransient
orstatic
. This method will override that behavior.This is a convenience method which behaves as if an
ExclusionStrategy
which excludes these fields was registered with this builder.- 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
@CanIgnoreReturnValue public GsonBuilder 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
@CanIgnoreReturnValue public GsonBuilder excludeFieldsWithoutExposeAnnotation()
Configures Gson to exclude all fields from consideration for serialization and deserialization that do not have theExpose
annotation.This is a convenience method which behaves as if an
ExclusionStrategy
which excludes these fields was registered with this builder.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern
-
serializeNulls
@CanIgnoreReturnValue public GsonBuilder serializeNulls()
Configures 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
@CanIgnoreReturnValue public GsonBuilder enableComplexMapKeySerialization()
Configures Gson to serializeMap
objects with complex keys as JSON arrays. 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 some
Point
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:
The above code prints this JSON object:Gson gson = new GsonBuilder() .register(Point.class, new MyPointTypeAdapter()) .enableComplexMapKeySerialization() .create(); Map<Point, String> original = new LinkedHashMap<>(); 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 some
Point
class, but rather the default Gson serialization is applied. In this case, somenew Point(2,3)
would serialize as{"x":2,"y":3}
.Given the assumption above, a
Map<Point, String>
will be serialized 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:
The JSON output would look as follows:Gson gson = new GsonBuilder() .enableComplexMapKeySerialization() .create(); Map<Point, String> original = new LinkedHashMap<>(); original.put(new Point(5, 6), "a"); original.put(new Point(8, 8), "b"); System.out.println(gson.toJson(original, type));
[ [ { "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
@CanIgnoreReturnValue public GsonBuilder disableInnerClassSerialization()
Configures Gson to exclude inner classes (= non-static
nested classes) during serialization and deserialization. This is a convenience method which behaves as if anExclusionStrategy
which excludes inner classes was registered with this builder. This means inner classes will be serialized as JSONnull
, and will be deserialized as Javanull
with their JSON data being ignored. And fields with an inner class as type will be ignored during serialization and deserialization.By default Gson serializes and deserializes inner classes, but ignores references to the enclosing instance. Deserialization might not be possible at all when
disableJdkUnsafe()
is used (and no customInstanceCreator
is registered), or it can lead to unexpectedNullPointerException
s when the deserialized instance is used afterwards.In general using inner classes with Gson should be avoided; they should be converted to
static
nested classes if possible.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - Since:
- 1.3
-
setLongSerializationPolicy
@CanIgnoreReturnValue public GsonBuilder setLongSerializationPolicy(LongSerializationPolicy serializationPolicy)
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
@CanIgnoreReturnValue public GsonBuilder setFieldNamingPolicy(FieldNamingPolicy namingConvention)
Configures Gson to apply a specific naming policy to an object's fields during serialization and deserialization.This method just delegates to
setFieldNamingStrategy(FieldNamingStrategy)
.
-
setFieldNamingStrategy
@CanIgnoreReturnValue public GsonBuilder setFieldNamingStrategy(FieldNamingStrategy fieldNamingStrategy)
Configures Gson to apply a specific naming strategy to an object's fields during serialization and deserialization.The created Gson instance might only use the field naming strategy once for a field and cache the result. It is not guaranteed that the strategy will be used again every time the value of a field is serialized or deserialized.
- Parameters:
fieldNamingStrategy
- the naming strategy to apply to the fields- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - Since:
- 1.3
-
setObjectToNumberStrategy
@CanIgnoreReturnValue public GsonBuilder setObjectToNumberStrategy(ToNumberStrategy objectToNumberStrategy)
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 - Since:
- 2.8.9
- See Also:
The default object-to-number strategy
-
setNumberToNumberStrategy
@CanIgnoreReturnValue public GsonBuilder setNumberToNumberStrategy(ToNumberStrategy numberToNumberStrategy)
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 - Since:
- 2.8.9
- See Also:
The default number-to-number strategy
-
setExclusionStrategies
@CanIgnoreReturnValue public GsonBuilder setExclusionStrategies(ExclusionStrategy... strategies)
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. The strategies are added to the existing strategies (if any); the existing strategies are not replaced.Fields are excluded for serialization and deserialization when
shouldSkipField
returnstrue
, or whenshouldSkipClass
returnstrue
for the field type. Gson behaves as if the field did not exist; its value is not serialized and on deserialization if a JSON member with this name exists it is skipped by default.
When objects of an excluded type (as determined byshouldSkipClass
) are serialized a JSON null is written to output, and when deserialized the JSON value is skipped andnull
is returned.The created Gson instance might only use an exclusion strategy once for a field or class and cache the result. It is not guaranteed that the strategy will be used again every time the value of a field or a class is serialized or deserialized.
- 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
@CanIgnoreReturnValue public GsonBuilder addSerializationExclusionStrategy(ExclusionStrategy strategy)
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.See the documentation of
setExclusionStrategies(ExclusionStrategy...)
for a detailed description of the effect of exclusion strategies.- 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
@CanIgnoreReturnValue public GsonBuilder addDeserializationExclusionStrategy(ExclusionStrategy strategy)
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.See the documentation of
setExclusionStrategies(ExclusionStrategy...)
for a detailed description of the effect of exclusion strategies.- 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
@CanIgnoreReturnValue public GsonBuilder setPrettyPrinting()
Configures Gson to output JSON that fits in a page for pretty printing. This option only affects JSON serialization.This is a convenience method which simply calls
setFormattingStyle(FormattingStyle)
withFormattingStyle.PRETTY
.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern
-
setFormattingStyle
@CanIgnoreReturnValue public GsonBuilder setFormattingStyle(FormattingStyle formattingStyle)
Configures Gson to output JSON that uses a certain kind of formatting style (for example newline and indent). This option only affects JSON serialization. By default Gson produces compact JSON output without any formatting.- Parameters:
formattingStyle
- the formatting style to use.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - Since:
- 2.11.0
-
setLenient
@Deprecated @InlineMe(replacement="this.setStrictness(Strictness.LENIENT)", imports="com.google.gson.Strictness") @CanIgnoreReturnValue public GsonBuilder setLenient()
Deprecated.This method is equivalent to callingsetStrictness(Strictness)
withStrictness.LENIENT
:setStrictness(Strictness.LENIENT)
Sets the strictness of this builder toStrictness.LENIENT
.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern. - See Also:
JsonReader.setStrictness(Strictness)
,JsonWriter.setStrictness(Strictness)
,setStrictness(Strictness)
-
setStrictness
@CanIgnoreReturnValue public GsonBuilder setStrictness(Strictness strictness)
Sets the strictness of this builder to the provided parameter.This changes how strict the RFC 8259 JSON specification is enforced when parsing or writing JSON. For details on this, refer to
JsonReader.setStrictness(Strictness)
andJsonWriter.setStrictness(Strictness)
.- Parameters:
strictness
- the new strictness mode. May not benull
.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern. - Since:
- 2.11.0
- See Also:
JsonReader.setStrictness(Strictness)
,JsonWriter.setStrictness(Strictness)
-
disableHtmlEscaping
@CanIgnoreReturnValue public GsonBuilder 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
@CanIgnoreReturnValue public GsonBuilder setDateFormat(String pattern)
Configures Gson to serializeDate
objects according to the pattern provided. You can call this method orsetDateFormat(int, 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; can benull
to reset the pattern- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - Throws:
IllegalArgumentException
- if the pattern is invalid- Since:
- 1.2
-
setDateFormat
@Deprecated @CanIgnoreReturnValue public GsonBuilder setDateFormat(int dateStyle)
Deprecated.Counterintuitively, despite this method taking only a 'date style' Gson will use a format which includes both date and time, with the 'time style' being the last value set bysetDateFormat(int, int)
. Therefore prefer usingsetDateFormat(int, int)
and explicitly provide the desired 'time style'.Configures Gson to serializeDate
objects according to the date 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. This methods leaves the current 'time style' unchanged.Note that this style value should be one of the predefined constants in the
DateFormat
class, such asDateFormat.MEDIUM
. See the documentation of theDateFormat
class for more information on the valid style constants.- Parameters:
dateStyle
- 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 - Throws:
IllegalArgumentException
- if the style is invalid- Since:
- 1.2
-
setDateFormat
@CanIgnoreReturnValue public GsonBuilder setDateFormat(int dateStyle, int timeStyle)
Configures Gson 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, such asDateFormat.MEDIUM
. See the documentation of theDateFormat
class 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 - Throws:
IllegalArgumentException
- if the style values are invalid- Since:
- 1.2
-
registerTypeAdapter
@CanIgnoreReturnValue public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter)
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
. And when registering an adapter for a class which has subclasses, you might also want to register the adapter for subclasses, or useregisterTypeHierarchyAdapter(Class, Object)
instead.JsonSerializer
andJsonDeserializer
are made "null
-safe". This means when trying to serializenull
, Gson will write a JSONnull
and the serializer is not called. Similarly when deserializing a JSONnull
, Gson will emitnull
without calling the deserializer. If it is desired to handlenull
values, aTypeAdapter
should be used instead.- 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 - Throws:
IllegalArgumentException
- if the type adapter being registered is forObject
class orJsonElement
or any of its subclasses- See Also:
registerTypeHierarchyAdapter(Class, Object)
-
registerTypeAdapterFactory
@CanIgnoreReturnValue public GsonBuilder registerTypeAdapterFactory(TypeAdapterFactory factory)
Registers 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.The created Gson instance might only use the factory once to create an adapter for a specific type and cache the result. It is not guaranteed that the factory will be used again every time the type is serialized or deserialized.
- Since:
- 2.1
-
registerTypeHierarchyAdapter
@CanIgnoreReturnValue public GsonBuilder registerTypeHierarchyAdapter(Class<?> baseType, Object typeAdapter)
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 - Throws:
IllegalArgumentException
- if the type adapter being registered is forJsonElement
or any of its subclasses- Since:
- 1.7
-
serializeSpecialFloatingPointValues
@CanIgnoreReturnValue public GsonBuilder serializeSpecialFloatingPointValues()
Section 6 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
-
disableJdkUnsafe
@CanIgnoreReturnValue public GsonBuilder disableJdkUnsafe()
Disables usage of JDK'ssun.misc.Unsafe
.By default Gson uses
Unsafe
to create instances of classes which don't have a no-args constructor. However,Unsafe
might not be available for all Java runtimes. For example Android does not provideUnsafe
, or only with limited functionality. AdditionallyUnsafe
creates instances without executing any constructor or initializer block, or performing initialization of field values. This can lead to surprising and difficult to debug errors. Therefore, to get reliable behavior regardless of which runtime is used, and to detect classes which cannot be deserialized in an early stage of development, this method allows disabling usage ofUnsafe
.- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - Since:
- 2.9.0
-
addReflectionAccessFilter
@CanIgnoreReturnValue public GsonBuilder addReflectionAccessFilter(ReflectionAccessFilter filter)
Adds a reflection access filter. A reflection access filter prevents Gson from using reflection for the serialization and deserialization of certain classes. The logic in the filter specifies which classes those are.Filters will be invoked in reverse registration order, that is, the most recently added filter will be invoked first.
By default Gson has no filters configured and will try to use reflection for all classes for which no
TypeAdapter
has been registered, and for which no built-in GsonTypeAdapter
exists.The created Gson instance might only use an access filter once for a class or its members and cache the result. It is not guaranteed that the filter will be used again every time a class or its members are accessed during serialization or deserialization.
- Parameters:
filter
- filter to add- Returns:
- a reference to this
GsonBuilder
object to fulfill the "Builder" pattern - Since:
- 2.9.1
-
-