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()).enableComplexMapKeySerialization()
.serializeNulls().setDateFormat(DateFormat.LONG).setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.setPrettyPrinting().setVersion(1.0).create();
NOTES:
Date and its subclasses in Gson does
not contain time-zone information. So, if you are using date/time instances,
use GsonBuilder and its setDateFormat methods.| Constructor and Description |
|---|
GsonBuilder()
Creates a GsonBuilder instance that can be used to build Gson with various
configuration settings.
|
| Modifier and Type | Method and Description |
|---|---|
GsonBuilder |
addDeserializationExclusionStrategy(ExclusionStrategy strategy)
Configures Gson to apply the passed in exclusion strategy during
deserialization.
|
GsonBuilder |
addSerializationExclusionStrategy(ExclusionStrategy strategy)
Configures Gson to apply the passed in exclusion strategy during
serialization.
|
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 |
enableComplexMapKeySerialization()
Enabling this feature will only change the serialized form if the map key is
a complex type (i.e.
|
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 |
registerTypeAdapterFactory(TypeAdapterFactory factory)
Register 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()
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 |
setLenient()
By default, Gson is strict and only accepts JSON as specified by
RFC 4627.
|
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.
|
public GsonBuilder()
create().public GsonBuilder setVersion(double ignoreVersionsAfter)
ignoreVersionsAfter - any field or type marked with a version higher
than this value are ignored during serialization
or deserialization.GsonBuilder object to fulfill the
"Builder" patternpublic GsonBuilder excludeFieldsWithModifiers(int... modifiers)
modifiers - the field modifiers. You must use the modifiers specified in
the Modifier class. For example,
Modifier.TRANSIENT,
Modifier.STATIC.GsonBuilder object to fulfill the
"Builder" patternpublic GsonBuilder generateNonExecutableJson()
GsonBuilder object to fulfill the
"Builder" patternpublic GsonBuilder excludeFieldsWithoutExposeAnnotation()
Expose annotation.GsonBuilder object to fulfill the
"Builder" patternpublic GsonBuilder serializeNulls()
GsonBuilder object to fulfill the
"Builder" patternpublic GsonBuilder enableComplexMapKeySerialization()
toString()
on the key; however, when this is called then one of the following cases
apply:
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 a
JsonObject.
Below is an example:
{
@code
Gson gson = new GsonBuilder().register(Point.class, new MyPointTypeAdapter()).enableComplexMapKeySerialization()
.create();
Map original = new LinkedHashMap();
original.put(new Point(5, 6), "a");
original.put(new Point(8, 8), "b");
System.out.println(gson.toJson(original, type));
}
The above code prints this JSON object:
{
"(5,6)": "a",
"(8,8)": "b"
}
Point class, but rather the default Gson
serialization is applied. In this case, some new 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" ] ]
GsonBuilder object to fulfill the
"Builder" patternpublic GsonBuilder disableInnerClassSerialization()
GsonBuilder object to fulfill the
"Builder" patternpublic GsonBuilder setLongSerializationPolicy(LongSerializationPolicy serializationPolicy)
Long and
long objects.serializationPolicy - the particular policy to use for serializing
longs.GsonBuilder object to fulfill the
"Builder" patternpublic GsonBuilder setFieldNamingPolicy(FieldNamingPolicy namingConvention)
namingConvention - the JSON field naming convention to use for
serialization and deserialization.GsonBuilder object to fulfill the
"Builder" patternpublic GsonBuilder setFieldNamingStrategy(FieldNamingStrategy fieldNamingStrategy)
fieldNamingStrategy - the actual naming strategy to apply to the fieldsGsonBuilder object to fulfill the
"Builder" patternpublic GsonBuilder setExclusionStrategies(ExclusionStrategy... strategies)
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 serialization/deserialization.strategies - the set of strategy object to apply during object
(de)serialization.GsonBuilder object to fulfill the
"Builder" patternpublic GsonBuilder addSerializationExclusionStrategy(ExclusionStrategy strategy)
strategy - an exclusion strategy to apply during serialization.GsonBuilder object to fulfill the
"Builder" patternpublic GsonBuilder addDeserializationExclusionStrategy(ExclusionStrategy strategy)
strategy - an exclusion strategy to apply during deserialization.GsonBuilder object to fulfill the
"Builder" patternpublic GsonBuilder setPrettyPrinting()
GsonBuilder object to fulfill the
"Builder" patternpublic GsonBuilder setLenient()
GsonBuilder object to fulfill the
"Builder" patternJsonReader.setLenient(boolean)public GsonBuilder disableHtmlEscaping()
GsonBuilder object to fulfill the
"Builder" patternpublic GsonBuilder setDateFormat(String pattern)
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.
The date format will be used to serialize and deserialize Date,
Timestamp and Date.
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.
pattern - the pattern that dates will be serialized/deserialized to/fromGsonBuilder object to fulfill the
"Builder" patternpublic GsonBuilder setDateFormat(int style)
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.
style - the predefined date style that date objects will be
serialized/deserialized to/fromGsonBuilder object to fulfill the
"Builder" patternpublic GsonBuilder setDateFormat(int dateStyle, int timeStyle)
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.
dateStyle - the predefined date style that date objects will be
serialized/deserialized to/fromtimeStyle - the predefined style for the time portion of the date
objectsGsonBuilder object to fulfill the
"Builder" patternpublic GsonBuilder registerTypeAdapter(Type type, Object typeAdapter)
TypeAdapter, 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 a type adapter was previously
registered for the specified type, 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 register Boolean.class.
type - the type definition for the type adapter being registeredtypeAdapter - This object must implement at least one of the
TypeAdapter, InstanceCreator,
JsonSerializer, and a JsonDeserializer
interfaces.GsonBuilder object to fulfill the
"Builder" patternpublic GsonBuilder registerTypeAdapterFactory(TypeAdapterFactory factory)
public GsonBuilder registerTypeHierarchyAdapter(Class<?> baseType, Object typeAdapter)
TypeAdapter, JsonSerializer and a JsonDeserializer.
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.baseType - the class definition for the type adapter being registered
for the base class or interfacetypeAdapter - This object must implement at least one of
TypeAdapter, JsonSerializer or
JsonDeserializer interfaces.GsonBuilder object to fulfill the
"Builder" patternpublic GsonBuilder serializeSpecialFloatingPointValues()
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 gamehandle these special values.
GsonBuilder object to fulfill the
"Builder" pattern