com.google.gson
Class GsonBuilder

java.lang.Object
  extended by com.google.gson.GsonBuilder

public final class GsonBuilder
extends Object

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())
     .serializeNulls()
     .setDateFormat(DateFormat.LONG)
     .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
     .setPrettyPrinting()
     .setVersion(1.0)
     .create();
 

NOTE: the order of invocation of configuration methods does not matter.

Author:
Inderjeet Singh, Joel Leitch

Constructor Summary
GsonBuilder()
          Creates a GsonBuilder instance that can be used to build Gson with various configuration settings.
 
Method Summary
 Gson create()
          Creates a Gson 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 during serialization.
 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 or deserialization that do not have the Expose 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 serializeNulls()
          Configure Gson to serialize null fields.
 GsonBuilder serializeSpecialFloatingPointValues()
          Section 2.4 of JSON specification disallows special double values (NaN, Infinity, -Infinity).
 GsonBuilder setDateFormat(int style)
          Configures Gson to to serialize Date objects according to the style value provided.
 GsonBuilder setDateFormat(int dateStyle, int timeStyle)
          Configures Gson to to serialize Date objects according to the style value provided.
 GsonBuilder setDateFormat(String pattern)
          Configures Gson to serialize Date 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 field during serialization and deserialization.
 GsonBuilder setFieldNamingStrategy(FieldNamingStrategy fieldNamingStrategy)
          Configures Gson to apply a specific naming policy strategy to an object's field during serialization and deserialization.
 GsonBuilder setLongSerializationPolicy(LongSerializationPolicy serializationPolicy)
          Configures Gson to apply a specific serialization policy for Long and long objects.
 GsonBuilder setPrettyPrinting()
          Configures Gson to output Json that fits in a page for pretty printing.
 GsonBuilder setVersion(double ignoreVersionsAfter)
          Configures Gson to enable versioning support.
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

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 calling create().

Method Detail

setVersion

public GsonBuilder setVersion(double ignoreVersionsAfter)
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

public GsonBuilder excludeFieldsWithModifiers(int... modifiers)
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 the Modifier class. For example, Modifier.TRANSIENT, Modifier.STATIC.
Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern

generateNonExecutableJson

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

public GsonBuilder excludeFieldsWithoutExposeAnnotation()
Configures Gson to exclude all fields from consideration for serialization or deserialization that do not have the Expose annotation.

Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern

serializeNulls

public GsonBuilder 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

disableInnerClassSerialization

public GsonBuilder 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

public GsonBuilder setLongSerializationPolicy(LongSerializationPolicy serializationPolicy)
Configures Gson to apply a specific serialization policy for Long and long 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

public GsonBuilder setFieldNamingPolicy(FieldNamingPolicy namingConvention)
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

public GsonBuilder setFieldNamingStrategy(FieldNamingStrategy fieldNamingStrategy)
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

setExclusionStrategies

public GsonBuilder setExclusionStrategies(ExclusionStrategy... strategies)
Configures Gson to apply a set of exclusion strategies during both serialization and deserialization. Each of the strategies will be applied as a disjunction rule. This means that if one of the strategies suggests that a field (or class) should be skipped then that field (or object) is skipped during serializaiton/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

setPrettyPrinting

public GsonBuilder 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

disableHtmlEscaping

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

public GsonBuilder setDateFormat(String pattern)
Configures Gson to serialize Date objects according to the pattern provided. You can call this method or setDateFormat(int) multiple times, but only the last invocation will be used to decide the serialization format.

Note that this pattern must abide by the convention provided by SimpleDateFormat class. See the documentation in SimpleDateFormat 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

public GsonBuilder setDateFormat(int style)
Configures Gson to to serialize Date objects according to the style value provided. You can call this method or setDateFormat(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 in DateFormat 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

public GsonBuilder setDateFormat(int dateStyle,
                                 int timeStyle)
Configures Gson to to serialize Date objects according to the style value provided. You can call this method or setDateFormat(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 in DateFormat for more information on the valid style constants.

Parameters:
dateStyle - the predefined date style that date objects will be serialized/deserialized to/from
timeStyle - 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

public GsonBuilder registerTypeAdapter(Type type,
                                       Object typeAdapter)
Configures Gson for custom serialization or deserialization. This method combines the registration of an InstanceCreator, JsonSerializer, and a JsonDeserializer. It is best used when a single object typeAdapter implements all the required interfaces for custom serialization with Gson. If an instance creator, serializer or deserializer was previously registered for the specified type, it is overwritten.

Parameters:
type - the type definition for the type adapter being registered
typeAdapter - This object must implement at least one of the InstanceCreator, JsonSerializer, and a JsonDeserializer interfaces.
Returns:
a reference to this GsonBuilder object to fulfill the "Builder" pattern

serializeSpecialFloatingPointValues

public GsonBuilder 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 value Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, it will throw an IllegalArgumentException. 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

public Gson create()
Creates a Gson instance based on the current configuration. This method is free of side-effects to this GsonBuilder instance and hence can be called multiple times.

Returns:
an instance of Gson configured with the options currently set in this builder


Copyright © 2008-2010. All Rights Reserved.