Class Gson
toJson(Object)
or fromJson(String, Class)
methods on it. Gson instances are Thread-safe so you can reuse them freely across multiple
threads.
You can create a Gson instance by invoking new Gson()
if the default configuration
is all you need. You can also use GsonBuilder
to build a Gson instance with various
configuration options such as versioning support, pretty printing, custom
JsonSerializer
s, JsonDeserializer
s, and InstanceCreator
s.
Here is an example of how Gson is used for a simple Class:
Gson gson = new Gson(); // Or use new GsonBuilder().create(); MyType target = new MyType(); String json = gson.toJson(target); // serializes target to Json MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2
If the object that your are serializing/deserializing is a ParameterizedType
(i.e. contains at least one type parameter and may be an array) then you must use the
toJson(Object, Type)
or fromJson(String, Type)
method. Here is an
example for serializing and deserializing a ParameterizedType
:
Type listType = new TypeToken<List<String>>() {}.getType(); List<String> target = new LinkedList<String>(); target.add("blah"); Gson gson = new Gson(); String json = gson.toJson(target, listType); List<String> target2 = gson.fromJson(json, listType);
See the Gson User Guide for a more complete set of examples.
- See Also:
-
Nested Class Summary
Nested Classes -
Field Summary
FieldsModifier and TypeFieldDescription(package private) final List<TypeAdapterFactory>
(package private) final List<TypeAdapterFactory>
private final ThreadLocal<Map<TypeToken<?>,
Gson.FutureTypeAdapter<?>>> This thread local guards against reentrant calls to getAdapter().(package private) final boolean
private final ConstructorConstructor
(package private) final String
(package private) final int
(package private) static final boolean
(package private) static final boolean
(package private) static final boolean
(package private) static final boolean
(package private) static final boolean
(package private) static final boolean
(package private) static final boolean
(package private) final Excluder
(package private) final List<TypeAdapterFactory>
(package private) final FieldNamingStrategy
(package private) final boolean
(package private) final boolean
(package private) final Map<Type,
InstanceCreator<?>> private static final String
private final JsonAdapterAnnotationTypeAdapterFactory
(package private) final boolean
(package private) final LongSerializationPolicy
private static final TypeToken<?>
(package private) final ToNumberStrategy
(package private) final ToNumberStrategy
(package private) final boolean
(package private) final boolean
(package private) final boolean
(package private) final int
private final Map<TypeToken<?>,
TypeAdapter<?>> -
Constructor Summary
ConstructorsConstructorDescriptionGson()
Constructs a Gson object with default configuration.Gson
(Excluder excluder, FieldNamingStrategy fieldNamingStrategy, Map<Type, InstanceCreator<?>> instanceCreators, boolean serializeNulls, boolean complexMapKeySerialization, boolean generateNonExecutableGson, boolean htmlSafe, boolean prettyPrinting, boolean lenient, boolean serializeSpecialFloatingPointValues, LongSerializationPolicy longSerializationPolicy, String datePattern, int dateStyle, int timeStyle, List<TypeAdapterFactory> builderFactories, List<TypeAdapterFactory> builderHierarchyFactories, List<TypeAdapterFactory> factoriesToBeAdded, ToNumberStrategy objectToNumberStrategy, ToNumberStrategy numberToNumberStrategy) -
Method Summary
Modifier and TypeMethodDescriptionprivate static void
assertFullConsumption
(Object obj, JsonReader reader) private static TypeAdapter<AtomicLong>
atomicLongAdapter
(TypeAdapter<Number> longAdapter) private static TypeAdapter<AtomicLongArray>
atomicLongArrayAdapter
(TypeAdapter<Number> longAdapter) (package private) static void
checkValidFloatingPoint
(double value) private TypeAdapter<Number>
doubleAdapter
(boolean serializeSpecialFloatingPointValues) excluder()
Deprecated.This method by accident exposes an internal Gson class; it might be removed in a future version.Returns the field naming strategy used by this Gson instance.private TypeAdapter<Number>
floatAdapter
(boolean serializeSpecialFloatingPointValues) <T> T
fromJson
(JsonElement json, Class<T> classOfT) This method deserializes the Json read from the specified parse tree into an object of the specified type.<T> T
fromJson
(JsonElement json, Type typeOfT) This method deserializes the Json read from the specified parse tree into an object of the specified type.<T> T
fromJson
(JsonReader reader, Type typeOfT) Reads the next JSON value fromreader
and convert it to an object of typetypeOfT
.<T> T
This method deserializes the Json read from the specified reader into an object of the specified class.<T> T
This method deserializes the Json read from the specified reader into an object of the specified type.<T> T
This method deserializes the specified Json into an object of the specified class.<T> T
This method deserializes the specified Json into an object of the specified type.<T> TypeAdapter<T>
getAdapter
(TypeToken<T> type) Returns the type adapter for type.<T> TypeAdapter<T>
getAdapter
(Class<T> type) Returns the type adapter for type.<T> TypeAdapter<T>
getDelegateAdapter
(TypeAdapterFactory skipPast, TypeToken<T> type) This method is used to get an alternate type adapter for the specified type.boolean
htmlSafe()
Returns whether this Gson instance produces JSON output which is HTML-safe, that means all HTML characters are escaped.private static TypeAdapter<Number>
longAdapter
(LongSerializationPolicy longSerializationPolicy) Returns a new GsonBuilder containing all custom factories and configuration used by the current instance.newJsonReader
(Reader reader) Returns a new JSON reader configured for the settings on this Gson instance.newJsonWriter
(Writer writer) Returns a new JSON writer configured for the settings on this Gson instance.boolean
Returns whether this Gson instance is serializing JSON object properties withnull
values, or just omits them.toJson
(JsonElement jsonElement) Converts a tree ofJsonElement
s into its equivalent JSON representation.void
toJson
(JsonElement jsonElement, JsonWriter writer) Writes the JSON forjsonElement
towriter
.void
toJson
(JsonElement jsonElement, Appendable writer) Writes out the equivalent JSON for a tree ofJsonElement
s.This method serializes the specified object into its equivalent Json representation.void
toJson
(Object src, Appendable writer) This method serializes the specified object into its equivalent Json representation.This method serializes the specified object, including those of generic types, into its equivalent Json representation.void
toJson
(Object src, Type typeOfSrc, JsonWriter writer) Writes the JSON representation ofsrc
of typetypeOfSrc
towriter
.void
toJson
(Object src, Type typeOfSrc, Appendable writer) This method serializes the specified object, including those of generic types, into its equivalent Json representation.toJsonTree
(Object src) This method serializes the specified object into its equivalent representation as a tree ofJsonElement
s.toJsonTree
(Object src, Type typeOfSrc) This method serializes the specified object, including those of generic types, into its equivalent representation as a tree ofJsonElement
s.toString()
-
Field Details
-
DEFAULT_JSON_NON_EXECUTABLE
static final boolean DEFAULT_JSON_NON_EXECUTABLE- See Also:
-
DEFAULT_LENIENT
static final boolean DEFAULT_LENIENT- See Also:
-
DEFAULT_PRETTY_PRINT
static final boolean DEFAULT_PRETTY_PRINT- See Also:
-
DEFAULT_ESCAPE_HTML
static final boolean DEFAULT_ESCAPE_HTML- See Also:
-
DEFAULT_SERIALIZE_NULLS
static final boolean DEFAULT_SERIALIZE_NULLS- See Also:
-
DEFAULT_COMPLEX_MAP_KEYS
static final boolean DEFAULT_COMPLEX_MAP_KEYS- See Also:
-
DEFAULT_SPECIALIZE_FLOAT_VALUES
static final boolean DEFAULT_SPECIALIZE_FLOAT_VALUES- See Also:
-
NULL_KEY_SURROGATE
-
JSON_NON_EXECUTABLE_PREFIX
- See Also:
-
calls
This thread local guards against reentrant calls to getAdapter(). In certain object graphs, creating an adapter for a type may recursively require an adapter for the same type! Without intervention, the recursive lookup would stack overflow. We cheat by returning a proxy type adapter. The proxy is wired up once the initial adapter has been created. -
typeTokenCache
-
constructorConstructor
-
jsonAdapterFactory
-
factories
-
excluder
-
fieldNamingStrategy
-
instanceCreators
-
serializeNulls
final boolean serializeNulls -
complexMapKeySerialization
final boolean complexMapKeySerialization -
generateNonExecutableJson
final boolean generateNonExecutableJson -
htmlSafe
final boolean htmlSafe -
prettyPrinting
final boolean prettyPrinting -
lenient
final boolean lenient -
serializeSpecialFloatingPointValues
final boolean serializeSpecialFloatingPointValues -
datePattern
-
dateStyle
final int dateStyle -
timeStyle
final int timeStyle -
longSerializationPolicy
-
builderFactories
-
builderHierarchyFactories
-
objectToNumberStrategy
-
numberToNumberStrategy
-
-
Constructor Details
-
Gson
public Gson()Constructs a Gson object with default configuration. The default configuration has the following settings:- The JSON generated by
toJson
methods is in compact representation. This means that all the unneeded white-space is removed. You can change this behavior withGsonBuilder.setPrettyPrinting()
. - The generated JSON omits all the fields that are null. Note that nulls in arrays are
kept as is since an array is an ordered list. Moreover, if a field is not null, but its
generated JSON is empty, the field is kept. You can configure Gson to serialize null values
by setting
GsonBuilder.serializeNulls()
. - Gson provides default serialization and deserialization for Enums,
Map
,URL
,URI
,Locale
,Date
,BigDecimal
, andBigInteger
classes. If you would prefer to change the default representation, you can do so by registering a type adapter throughGsonBuilder.registerTypeAdapter(Type, Object)
. - The default Date format is same as
DateFormat.DEFAULT
. This format ignores the millisecond portion of the date during serialization. You can change this by invokingGsonBuilder.setDateFormat(int)
orGsonBuilder.setDateFormat(String)
. - By default, Gson ignores the
Expose
annotation. You can enable Gson to serialize/deserialize only those fields marked with this annotation throughGsonBuilder.excludeFieldsWithoutExposeAnnotation()
. - By default, Gson ignores the
Since
annotation. You can enable Gson to use this annotation throughGsonBuilder.setVersion(double)
. - The default field naming policy for the output Json is same as in Java. So, a Java class
field
versionNumber
will be output as"versionNumber"
in Json. The same rules are applied for mapping incoming Json to the Java classes. You can change this policy throughGsonBuilder.setFieldNamingPolicy(FieldNamingPolicy)
. - By default, Gson excludes
transient
orstatic
fields from consideration for serialization and deserialization. You can change this behavior throughGsonBuilder.excludeFieldsWithModifiers(int...)
.
- The JSON generated by
-
Gson
Gson(Excluder excluder, FieldNamingStrategy fieldNamingStrategy, Map<Type, InstanceCreator<?>> instanceCreators, boolean serializeNulls, boolean complexMapKeySerialization, boolean generateNonExecutableGson, boolean htmlSafe, boolean prettyPrinting, boolean lenient, boolean serializeSpecialFloatingPointValues, LongSerializationPolicy longSerializationPolicy, String datePattern, int dateStyle, int timeStyle, List<TypeAdapterFactory> builderFactories, List<TypeAdapterFactory> builderHierarchyFactories, List<TypeAdapterFactory> factoriesToBeAdded, ToNumberStrategy objectToNumberStrategy, ToNumberStrategy numberToNumberStrategy)
-
-
Method Details
-
newBuilder
Returns a new GsonBuilder containing all custom factories and configuration used by the current instance.- Returns:
- a GsonBuilder instance.
-
excluder
Deprecated.This method by accident exposes an internal Gson class; it might be removed in a future version. -
fieldNamingStrategy
Returns the field naming strategy used by this Gson instance. -
serializeNulls
public boolean serializeNulls()Returns whether this Gson instance is serializing JSON object properties withnull
values, or just omits them.- See Also:
-
htmlSafe
public boolean htmlSafe()Returns whether this Gson instance produces JSON output which is HTML-safe, that means all HTML characters are escaped.- See Also:
-
doubleAdapter
-
floatAdapter
-
checkValidFloatingPoint
static void checkValidFloatingPoint(double value) -
longAdapter
-
atomicLongAdapter
-
atomicLongArrayAdapter
-
getAdapter
Returns the type adapter for type.- Throws:
IllegalArgumentException
- if this GSON cannot serialize and deserializetype
.
-
getDelegateAdapter
This method is used to get an alternate type adapter for the specified type. This is used to access a type adapter that is overridden by aTypeAdapterFactory
that you may have registered. This features is typically used when you want to register a type adapter that does a little bit of work but then delegates further processing to the Gson default type adapter. Here is an example:Let's say we want to write a type adapter that counts the number of objects being read from or written to JSON. We can achieve this by writing a type adapter factory that uses the
getDelegateAdapter
method:class StatsTypeAdapterFactory implements TypeAdapterFactory { public int numReads = 0; public int numWrites = 0; public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); return new TypeAdapter<T>() { public void write(JsonWriter out, T value) throws IOException { ++numWrites; delegate.write(out, value); } public T read(JsonReader in) throws IOException { ++numReads; return delegate.read(in); } }; } }
StatsTypeAdapterFactory stats = new StatsTypeAdapterFactory(); Gson gson = new GsonBuilder().registerTypeAdapterFactory(stats).create(); // Call gson.toJson() and fromJson methods on objects System.out.println("Num JSON reads" + stats.numReads); System.out.println("Num JSON writes" + stats.numWrites);
skipPast
. In case of multiple TypeAdapterFactories registered it is up to the caller of this function to insure that the order of registration does not prevent this method from reaching a factory they would expect to reply from this call. Note that since you can not override type adapter factories for String and Java primitive types, our stats factory will not count the number of String or primitives that will be read or written.- Parameters:
skipPast
- The type adapter factory that needs to be skipped while searching for a matching type adapter. In most cases, you should just pass this (the type adapter factory from wheregetDelegateAdapter(com.google.gson.TypeAdapterFactory, com.google.gson.reflect.TypeToken<T>)
method is being invoked).type
- Type for which the delegate adapter is being searched for.- Since:
- 2.2
-
getAdapter
Returns the type adapter for type.- Throws:
IllegalArgumentException
- if this GSON cannot serialize and deserializetype
.
-
toJsonTree
This method serializes the specified object into its equivalent representation as a tree ofJsonElement
s. This method should be used when the specified object is not a generic type. This method usesObject.getClass()
to get the type for the specified object, but thegetClass()
loses the generic type information because of the Type Erasure feature of Java. Note that this method works fine if the any of the object fields are of generic type, just the object itself should not be of a generic type. If the object is of generic type, usetoJsonTree(Object, Type)
instead.- Parameters:
src
- the object for which Json representation is to be created setting for Gson- Returns:
- Json representation of
src
. - Since:
- 1.4
-
toJsonTree
This method serializes the specified object, including those of generic types, into its equivalent representation as a tree ofJsonElement
s. This method must be used if the specified object is a generic type. For non-generic objects, usetoJsonTree(Object)
instead.- Parameters:
src
- the object for which JSON representation is to be createdtypeOfSrc
- The specific genericized type of src. You can obtain this type by using theTypeToken
class. For example, to get the type forCollection<Foo>
, you should use:Type typeOfSrc = new TypeToken<Collection<Foo>>(){}.getType();
- Returns:
- Json representation of
src
- Since:
- 1.4
-
toJson
This method serializes the specified object into its equivalent Json representation. This method should be used when the specified object is not a generic type. This method usesObject.getClass()
to get the type for the specified object, but thegetClass()
loses the generic type information because of the Type Erasure feature of Java. Note that this method works fine if the any of the object fields are of generic type, just the object itself should not be of a generic type. If the object is of generic type, usetoJson(Object, Type)
instead. If you want to write out the object to aWriter
, usetoJson(Object, Appendable)
instead.- Parameters:
src
- the object for which Json representation is to be created setting for Gson- Returns:
- Json representation of
src
.
-
toJson
This method serializes the specified object, including those of generic types, into its equivalent Json representation. This method must be used if the specified object is a generic type. For non-generic objects, usetoJson(Object)
instead. If you want to write out the object to aAppendable
, usetoJson(Object, Type, Appendable)
instead.- Parameters:
src
- the object for which JSON representation is to be createdtypeOfSrc
- The specific genericized type of src. You can obtain this type by using theTypeToken
class. For example, to get the type forCollection<Foo>
, you should use:Type typeOfSrc = new TypeToken<Collection<Foo>>(){}.getType();
- Returns:
- Json representation of
src
-
toJson
This method serializes the specified object into its equivalent Json representation. This method should be used when the specified object is not a generic type. This method usesObject.getClass()
to get the type for the specified object, but thegetClass()
loses the generic type information because of the Type Erasure feature of Java. Note that this method works fine if the any of the object fields are of generic type, just the object itself should not be of a generic type. If the object is of generic type, usetoJson(Object, Type, Appendable)
instead.- Parameters:
src
- the object for which Json representation is to be created setting for Gsonwriter
- Writer to which the Json representation needs to be written- Throws:
JsonIOException
- if there was a problem writing to the writer- Since:
- 1.2
-
toJson
This method serializes the specified object, including those of generic types, into its equivalent Json representation. This method must be used if the specified object is a generic type. For non-generic objects, usetoJson(Object, Appendable)
instead.- Parameters:
src
- the object for which JSON representation is to be createdtypeOfSrc
- The specific genericized type of src. You can obtain this type by using theTypeToken
class. For example, to get the type forCollection<Foo>
, you should use:Type typeOfSrc = new TypeToken<Collection<Foo>>(){}.getType();
writer
- Writer to which the Json representation of src needs to be written.- Throws:
JsonIOException
- if there was a problem writing to the writer- Since:
- 1.2
-
toJson
Writes the JSON representation ofsrc
of typetypeOfSrc
towriter
.- Throws:
JsonIOException
- if there was a problem writing to the writer
-
toJson
Converts a tree ofJsonElement
s into its equivalent JSON representation.- Parameters:
jsonElement
- root of a tree ofJsonElement
s- Returns:
- JSON String representation of the tree
- Since:
- 1.4
-
toJson
Writes out the equivalent JSON for a tree ofJsonElement
s.- Parameters:
jsonElement
- root of a tree ofJsonElement
swriter
- Writer to which the Json representation needs to be written- Throws:
JsonIOException
- if there was a problem writing to the writer- Since:
- 1.4
-
newJsonWriter
Returns a new JSON writer configured for the settings on this Gson instance.- Throws:
IOException
-
newJsonReader
Returns a new JSON reader configured for the settings on this Gson instance. -
toJson
Writes the JSON forjsonElement
towriter
.- Throws:
JsonIOException
- if there was a problem writing to the writer
-
fromJson
This method deserializes the specified Json into an object of the specified class. It is not suitable to use if the specified class is a generic type since it will not have the generic type information because of the Type Erasure feature of Java. Therefore, this method should not be used if the desired type is a generic type. Note that this method works fine if the any of the fields of the specified object are generics, just the object itself should not be a generic type. For the cases when the object is of generic type, invokefromJson(String, Type)
. If you have the Json in aReader
instead of a String, usefromJson(Reader, Class)
instead.- Type Parameters:
T
- the type of the desired object- Parameters:
json
- the string from which the object is to be deserializedclassOfT
- the class of T- Returns:
- an object of type T from the string. Returns
null
ifjson
isnull
or ifjson
is empty. - Throws:
JsonSyntaxException
- if json is not a valid representation for an object of type classOfT
-
fromJson
This method deserializes the specified Json into an object of the specified type. This method is useful if the specified object is a generic type. For non-generic objects, usefromJson(String, Class)
instead. If you have the Json in aReader
instead of a String, usefromJson(Reader, Type)
instead.- Type Parameters:
T
- the type of the desired object- Parameters:
json
- the string from which the object is to be deserializedtypeOfT
- The specific genericized type of src. You can obtain this type by using theTypeToken
class. For example, to get the type forCollection<Foo>
, you should use:Type typeOfT = new TypeToken<Collection<Foo>>(){}.getType();
- Returns:
- an object of type T from the string. Returns
null
ifjson
isnull
or ifjson
is empty. - Throws:
JsonParseException
- if json is not a valid representation for an object of type typeOfTJsonSyntaxException
- if json is not a valid representation for an object of type
-
fromJson
This method deserializes the Json read from the specified reader into an object of the specified class. It is not suitable to use if the specified class is a generic type since it will not have the generic type information because of the Type Erasure feature of Java. Therefore, this method should not be used if the desired type is a generic type. Note that this method works fine if the any of the fields of the specified object are generics, just the object itself should not be a generic type. For the cases when the object is of generic type, invokefromJson(Reader, Type)
. If you have the Json in a String form instead of aReader
, usefromJson(String, Class)
instead.- Type Parameters:
T
- the type of the desired object- Parameters:
json
- the reader producing the Json from which the object is to be deserialized.classOfT
- the class of T- Returns:
- an object of type T from the string. Returns
null
ifjson
is at EOF. - Throws:
JsonIOException
- if there was a problem reading from the ReaderJsonSyntaxException
- if json is not a valid representation for an object of type- Since:
- 1.2
-
fromJson
This method deserializes the Json read from the specified reader into an object of the specified type. This method is useful if the specified object is a generic type. For non-generic objects, usefromJson(Reader, Class)
instead. If you have the Json in a String form instead of aReader
, usefromJson(String, Type)
instead.- Type Parameters:
T
- the type of the desired object- Parameters:
json
- the reader producing Json from which the object is to be deserializedtypeOfT
- The specific genericized type of src. You can obtain this type by using theTypeToken
class. For example, to get the type forCollection<Foo>
, you should use:Type typeOfT = new TypeToken<Collection<Foo>>(){}.getType();
- Returns:
- an object of type T from the json. Returns
null
ifjson
is at EOF. - Throws:
JsonIOException
- if there was a problem reading from the ReaderJsonSyntaxException
- if json is not a valid representation for an object of type- Since:
- 1.2
-
assertFullConsumption
-
fromJson
Reads the next JSON value fromreader
and convert it to an object of typetypeOfT
. Returnsnull
, if thereader
is at EOF. Since Type is not parameterized by T, this method is type unsafe and should be used carefully- Throws:
JsonIOException
- if there was a problem writing to the ReaderJsonSyntaxException
- if json is not a valid representation for an object of type
-
fromJson
This method deserializes the Json read from the specified parse tree into an object of the specified type. It is not suitable to use if the specified class is a generic type since it will not have the generic type information because of the Type Erasure feature of Java. Therefore, this method should not be used if the desired type is a generic type. Note that this method works fine if the any of the fields of the specified object are generics, just the object itself should not be a generic type. For the cases when the object is of generic type, invokefromJson(JsonElement, Type)
.- Type Parameters:
T
- the type of the desired object- Parameters:
json
- the root of the parse tree ofJsonElement
s from which the object is to be deserializedclassOfT
- The class of T- Returns:
- an object of type T from the json. Returns
null
ifjson
isnull
or ifjson
is empty. - Throws:
JsonSyntaxException
- if json is not a valid representation for an object of type typeOfT- Since:
- 1.3
-
fromJson
This method deserializes the Json read from the specified parse tree into an object of the specified type. This method is useful if the specified object is a generic type. For non-generic objects, usefromJson(JsonElement, Class)
instead.- Type Parameters:
T
- the type of the desired object- Parameters:
json
- the root of the parse tree ofJsonElement
s from which the object is to be deserializedtypeOfT
- The specific genericized type of src. You can obtain this type by using theTypeToken
class. For example, to get the type forCollection<Foo>
, you should use:Type typeOfT = new TypeToken<Collection<Foo>>(){}.getType();
- Returns:
- an object of type T from the json. Returns
null
ifjson
isnull
or ifjson
is empty. - Throws:
JsonSyntaxException
- if json is not a valid representation for an object of type typeOfT- Since:
- 1.3
-
toString
-