Class Gson
- java.lang.Object
-
- com.google.gson.Gson
-
public final class Gson extends java.lang.ObjectThis is the main class for using Gson. Gson is typically used by first constructing a Gson instance and then invokingtoJson(Object)orfromJson(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 useGsonBuilderto build a Gson instance with various configuration options such as versioning support, pretty printing, custom newline, custom indent, customJsonSerializers,JsonDeserializers, andInstanceCreators.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 type of the object that you are converting is a
ParameterizedType(i.e. has at least one type argument, for exampleList<MyType>) then for deserialization you must use afromJsonmethod withTypeorTypeTokenparameter to specify the parameterized type. For serialization specifying aTypeorTypeTokenis optional, otherwise Gson will use the runtime type of the object.TypeTokenis a class provided by Gson which helps creating parameterized types. Here is an example showing how this can be done:TypeToken<List<MyType>> listType = new TypeToken<List<MyType>>() {}; List<MyType> target = new LinkedList<MyType>(); target.add(new MyType(1, "abc")); Gson gson = new Gson(); // For serialization you normally do not have to specify the type, Gson will use // the runtime type of the objects, however you can also specify it explicitly String json = gson.toJson(target, listType.getType()); // But for deserialization you have to specify the type List<MyType> target2 = gson.fromJson(json, listType);See the Gson User Guide for a more complete set of examples.
JSON Strictness handling
For legacy reasons most of theGsonmethods allow JSON data which does not comply with the JSON specification when no explicit strictness is set (the default). To specify the strictness of aGsoninstance, you should set it throughGsonBuilder.setStrictness(Strictness).For older Gson versions, which don't have the strictness mode API, the following workarounds can be used:
Serialization
- Use
getAdapter(Class)to obtain the adapter for the type to be serialized - When using an existing
JsonWriter, manually apply the writer settings of thisGsoninstance listed bynewJsonWriter(Writer).
Otherwise, when not using an existingJsonWriter, usenewJsonWriter(Writer)to construct one. - Call
TypeAdapter.write(JsonWriter, Object)
Deserialization
- Use
getAdapter(Class)to obtain the adapter for the type to be deserialized - When using an existing
JsonReader, manually apply the reader settings of thisGsoninstance listed bynewJsonReader(Reader).
Otherwise, when not using an existingJsonReader, usenewJsonReader(Reader)to construct one. - Call
TypeAdapter.read(JsonReader) - Call
JsonReader.peek()and verify that the result isJsonToken.END_DOCUMENTto make sure there is no trailing data
JsonReadercreated this way is only 'legacy strict', it mostly adheres to the JSON specification but allows small deviations. SeeJsonReader.setStrictness(Strictness)for details.- See Also:
TypeToken
- Use
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description (package private) static classGson.FutureTypeAdapter<T>Proxy type adapter for cyclic type graphs.
-
Field Summary
Fields Modifier and Type Field Description (package private) java.util.List<TypeAdapterFactory>builderFactories(package private) java.util.List<TypeAdapterFactory>builderHierarchyFactories(package private) booleancomplexMapKeySerializationprivate ConstructorConstructorconstructorConstructor(package private) java.lang.StringdatePattern(package private) intdateStyle(package private) static booleanDEFAULT_COMPLEX_MAP_KEYS(package private) static java.lang.StringDEFAULT_DATE_PATTERN(package private) static booleanDEFAULT_ESCAPE_HTML(package private) static FieldNamingStrategyDEFAULT_FIELD_NAMING_STRATEGY(package private) static FormattingStyleDEFAULT_FORMATTING_STYLE(package private) static booleanDEFAULT_JSON_NON_EXECUTABLE(package private) static ToNumberStrategyDEFAULT_NUMBER_TO_NUMBER_STRATEGY(package private) static ToNumberStrategyDEFAULT_OBJECT_TO_NUMBER_STRATEGY(package private) static booleanDEFAULT_SERIALIZE_NULLS(package private) static booleanDEFAULT_SPECIALIZE_FLOAT_VALUES(package private) static StrictnessDEFAULT_STRICTNESS(package private) static booleanDEFAULT_USE_JDK_UNSAFE(package private) Excluderexcluder(package private) java.util.List<TypeAdapterFactory>factories(package private) FieldNamingStrategyfieldNamingStrategy(package private) FormattingStyleformattingStyle(package private) booleangenerateNonExecutableJson(package private) booleanhtmlSafe(package private) java.util.Map<java.lang.reflect.Type,InstanceCreator<?>>instanceCreatorsprivate static java.lang.StringJSON_NON_EXECUTABLE_PREFIXprivate JsonAdapterAnnotationTypeAdapterFactoryjsonAdapterFactory(package private) LongSerializationPolicylongSerializationPolicy(package private) ToNumberStrategynumberToNumberStrategy(package private) ToNumberStrategyobjectToNumberStrategy(package private) java.util.List<ReflectionAccessFilter>reflectionFilters(package private) booleanserializeNulls(package private) booleanserializeSpecialFloatingPointValues(package private) Strictnessstrictnessprivate java.lang.ThreadLocal<java.util.Map<TypeToken<?>,TypeAdapter<?>>>threadLocalAdapterResultsThis thread local guards against reentrant calls togetAdapter(TypeToken).(package private) inttimeStyleprivate java.util.concurrent.ConcurrentMap<TypeToken<?>,TypeAdapter<?>>typeTokenCache(package private) booleanuseJdkUnsafe
-
Constructor Summary
Constructors Constructor Description Gson()Constructs a Gson object with default configuration.Gson(Excluder excluder, FieldNamingStrategy fieldNamingStrategy, java.util.Map<java.lang.reflect.Type,InstanceCreator<?>> instanceCreators, boolean serializeNulls, boolean complexMapKeySerialization, boolean generateNonExecutableGson, boolean htmlSafe, FormattingStyle formattingStyle, Strictness strictness, boolean serializeSpecialFloatingPointValues, boolean useJdkUnsafe, LongSerializationPolicy longSerializationPolicy, java.lang.String datePattern, int dateStyle, int timeStyle, java.util.List<TypeAdapterFactory> builderFactories, java.util.List<TypeAdapterFactory> builderHierarchyFactories, java.util.List<TypeAdapterFactory> factoriesToBeAdded, ToNumberStrategy objectToNumberStrategy, ToNumberStrategy numberToNumberStrategy, java.util.List<ReflectionAccessFilter> reflectionFilters)
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description private static voidassertFullConsumption(java.lang.Object obj, JsonReader reader)private static TypeAdapter<java.util.concurrent.atomic.AtomicLong>atomicLongAdapter(TypeAdapter<java.lang.Number> longAdapter)private static TypeAdapter<java.util.concurrent.atomic.AtomicLongArray>atomicLongArrayAdapter(TypeAdapter<java.lang.Number> longAdapter)(package private) static voidcheckValidFloatingPoint(double value)private TypeAdapter<java.lang.Number>doubleAdapter(boolean serializeSpecialFloatingPointValues)Excluderexcluder()Deprecated.This method by accident exposes an internal Gson class; it might be removed in a future version.FieldNamingStrategyfieldNamingStrategy()Returns the field naming strategy used by this Gson instance.private TypeAdapter<java.lang.Number>floatAdapter(boolean serializeSpecialFloatingPointValues)<T> TfromJson(JsonElement json, TypeToken<T> typeOfT)This method deserializes the JSON read from the specified parse tree into an object of the specified type.<T> TfromJson(JsonElement json, java.lang.Class<T> classOfT)This method deserializes the JSON read from the specified parse tree into an object of the specified type.<T> TfromJson(JsonElement json, java.lang.reflect.Type typeOfT)This method deserializes the JSON read from the specified parse tree into an object of the specified type.<T> TfromJson(JsonReader reader, TypeToken<T> typeOfT)Reads the next JSON value fromreaderand converts it to an object of typetypeOfT.<T> TfromJson(JsonReader reader, java.lang.reflect.Type typeOfT)Reads the next JSON value fromreaderand converts it to an object of typetypeOfT.<T> TfromJson(java.io.Reader json, TypeToken<T> typeOfT)This method deserializes the JSON read from the specified reader into an object of the specified type.<T> TfromJson(java.io.Reader json, java.lang.Class<T> classOfT)This method deserializes the JSON read from the specified reader into an object of the specified class.<T> TfromJson(java.io.Reader json, java.lang.reflect.Type typeOfT)This method deserializes the JSON read from the specified reader into an object of the specified type.<T> TfromJson(java.lang.String json, TypeToken<T> typeOfT)This method deserializes the specified JSON into an object of the specified type.<T> TfromJson(java.lang.String json, java.lang.Class<T> classOfT)This method deserializes the specified JSON into an object of the specified class.<T> TfromJson(java.lang.String json, java.lang.reflect.Type typeOfT)This method deserializes the specified JSON into an object of the specified type.<T> TypeAdapter<T>getAdapter(TypeToken<T> type)Returns the type adapter fortype.<T> TypeAdapter<T>getAdapter(java.lang.Class<T> type)Returns the type adapter fortype.<T> TypeAdapter<T>getDelegateAdapter(TypeAdapterFactory skipPast, TypeToken<T> type)This method is used to get an alternate type adapter for the specified type.booleanhtmlSafe()Returns whether this Gson instance produces JSON output which is HTML-safe, that means all HTML characters are escaped.private static TypeAdapter<java.lang.Number>longAdapter(LongSerializationPolicy longSerializationPolicy)GsonBuildernewBuilder()Returns a new GsonBuilder containing all custom factories and configuration used by the current instance.JsonReadernewJsonReader(java.io.Reader reader)Returns a new JSON reader configured for the settings on this Gson instance.JsonWriternewJsonWriter(java.io.Writer writer)Returns a new JSON writer configured for the settings on this Gson instance.booleanserializeNulls()Returns whether this Gson instance is serializing JSON object properties withnullvalues, or just omits them.java.lang.StringtoJson(JsonElement jsonElement)Converts a tree ofJsonElements into its equivalent JSON representation.voidtoJson(JsonElement jsonElement, JsonWriter writer)Writes the JSON forjsonElementtowriter.voidtoJson(JsonElement jsonElement, java.lang.Appendable writer)Writes out the equivalent JSON for a tree ofJsonElements.java.lang.StringtoJson(java.lang.Object src)This method serializes the specified object into its equivalent JSON representation.voidtoJson(java.lang.Object src, java.lang.Appendable writer)This method serializes the specified object into its equivalent JSON representation and writes it to the writer.java.lang.StringtoJson(java.lang.Object src, java.lang.reflect.Type typeOfSrc)This method serializes the specified object, including those of generic types, into its equivalent JSON representation.voidtoJson(java.lang.Object src, java.lang.reflect.Type typeOfSrc, JsonWriter writer)Writes the JSON representation ofsrcof typetypeOfSrctowriter.voidtoJson(java.lang.Object src, java.lang.reflect.Type typeOfSrc, java.lang.Appendable writer)This method serializes the specified object, including those of generic types, into its equivalent JSON representation and writes it to the writer.JsonElementtoJsonTree(java.lang.Object src)This method serializes the specified object into its equivalent representation as a tree ofJsonElements.JsonElementtoJsonTree(java.lang.Object src, java.lang.reflect.Type typeOfSrc)This method serializes the specified object, including those of generic types, into its equivalent representation as a tree ofJsonElements.java.lang.StringtoString()
-
-
-
Field Detail
-
DEFAULT_JSON_NON_EXECUTABLE
static final boolean DEFAULT_JSON_NON_EXECUTABLE
- See Also:
- Constant Field Values
-
DEFAULT_STRICTNESS
static final Strictness DEFAULT_STRICTNESS
-
DEFAULT_FORMATTING_STYLE
static final FormattingStyle DEFAULT_FORMATTING_STYLE
-
DEFAULT_ESCAPE_HTML
static final boolean DEFAULT_ESCAPE_HTML
- See Also:
- Constant Field Values
-
DEFAULT_SERIALIZE_NULLS
static final boolean DEFAULT_SERIALIZE_NULLS
- See Also:
- Constant Field Values
-
DEFAULT_COMPLEX_MAP_KEYS
static final boolean DEFAULT_COMPLEX_MAP_KEYS
- See Also:
- Constant Field Values
-
DEFAULT_SPECIALIZE_FLOAT_VALUES
static final boolean DEFAULT_SPECIALIZE_FLOAT_VALUES
- See Also:
- Constant Field Values
-
DEFAULT_USE_JDK_UNSAFE
static final boolean DEFAULT_USE_JDK_UNSAFE
- See Also:
- Constant Field Values
-
DEFAULT_DATE_PATTERN
static final java.lang.String DEFAULT_DATE_PATTERN
-
DEFAULT_FIELD_NAMING_STRATEGY
static final FieldNamingStrategy DEFAULT_FIELD_NAMING_STRATEGY
-
DEFAULT_OBJECT_TO_NUMBER_STRATEGY
static final ToNumberStrategy DEFAULT_OBJECT_TO_NUMBER_STRATEGY
-
DEFAULT_NUMBER_TO_NUMBER_STRATEGY
static final ToNumberStrategy DEFAULT_NUMBER_TO_NUMBER_STRATEGY
-
JSON_NON_EXECUTABLE_PREFIX
private static final java.lang.String JSON_NON_EXECUTABLE_PREFIX
- See Also:
- Constant Field Values
-
threadLocalAdapterResults
private final java.lang.ThreadLocal<java.util.Map<TypeToken<?>,TypeAdapter<?>>> threadLocalAdapterResults
This thread local guards against reentrant calls togetAdapter(TypeToken). 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,Gson.FutureTypeAdapter, which is wired up once the initial adapter has been created.The map stores the type adapters for ongoing
getAdaptercalls, with the type token provided togetAdapteras key and eitherFutureTypeAdapteror a regularTypeAdapteras value.
-
typeTokenCache
private final java.util.concurrent.ConcurrentMap<TypeToken<?>,TypeAdapter<?>> typeTokenCache
-
constructorConstructor
private final ConstructorConstructor constructorConstructor
-
jsonAdapterFactory
private final JsonAdapterAnnotationTypeAdapterFactory jsonAdapterFactory
-
factories
final java.util.List<TypeAdapterFactory> factories
-
excluder
final Excluder excluder
-
fieldNamingStrategy
final FieldNamingStrategy fieldNamingStrategy
-
instanceCreators
final java.util.Map<java.lang.reflect.Type,InstanceCreator<?>> instanceCreators
-
serializeNulls
final boolean serializeNulls
-
complexMapKeySerialization
final boolean complexMapKeySerialization
-
generateNonExecutableJson
final boolean generateNonExecutableJson
-
htmlSafe
final boolean htmlSafe
-
formattingStyle
final FormattingStyle formattingStyle
-
strictness
final Strictness strictness
-
serializeSpecialFloatingPointValues
final boolean serializeSpecialFloatingPointValues
-
useJdkUnsafe
final boolean useJdkUnsafe
-
datePattern
final java.lang.String datePattern
-
dateStyle
final int dateStyle
-
timeStyle
final int timeStyle
-
longSerializationPolicy
final LongSerializationPolicy longSerializationPolicy
-
builderFactories
final java.util.List<TypeAdapterFactory> builderFactories
-
builderHierarchyFactories
final java.util.List<TypeAdapterFactory> builderHierarchyFactories
-
objectToNumberStrategy
final ToNumberStrategy objectToNumberStrategy
-
numberToNumberStrategy
final ToNumberStrategy numberToNumberStrategy
-
reflectionFilters
final java.util.List<ReflectionAccessFilter> reflectionFilters
-
-
Constructor Detail
-
Gson
public Gson()
Constructs a Gson object with default configuration. The default configuration has the following settings:- The JSON generated by
toJsonmethods is in compact representation. This means that all the unneeded white-space is removed. You can change this behavior withGsonBuilder.setPrettyPrinting(). - When the JSON generated contains more than one line, the kind of newline and indent to
use can be configured with
GsonBuilder.setFormattingStyle(FormattingStyle). - 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, andBigIntegerclasses. 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, int)orGsonBuilder.setDateFormat(String). - By default, Gson ignores the
Exposeannotation. You can enable Gson to serialize/deserialize only those fields marked with this annotation throughGsonBuilder.excludeFieldsWithoutExposeAnnotation(). - By default, Gson ignores the
Sinceannotation. 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
versionNumberwill 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
transientorstaticfields from consideration for serialization and deserialization. You can change this behavior throughGsonBuilder.excludeFieldsWithModifiers(int...). - No explicit strictness is set. You can change this by calling
GsonBuilder.setStrictness(Strictness).
- The JSON generated by
-
Gson
Gson(Excluder excluder, FieldNamingStrategy fieldNamingStrategy, java.util.Map<java.lang.reflect.Type,InstanceCreator<?>> instanceCreators, boolean serializeNulls, boolean complexMapKeySerialization, boolean generateNonExecutableGson, boolean htmlSafe, FormattingStyle formattingStyle, Strictness strictness, boolean serializeSpecialFloatingPointValues, boolean useJdkUnsafe, LongSerializationPolicy longSerializationPolicy, java.lang.String datePattern, int dateStyle, int timeStyle, java.util.List<TypeAdapterFactory> builderFactories, java.util.List<TypeAdapterFactory> builderHierarchyFactories, java.util.List<TypeAdapterFactory> factoriesToBeAdded, ToNumberStrategy objectToNumberStrategy, ToNumberStrategy numberToNumberStrategy, java.util.List<ReflectionAccessFilter> reflectionFilters)
-
-
Method Detail
-
newBuilder
public GsonBuilder newBuilder()
Returns a new GsonBuilder containing all custom factories and configuration used by the current instance.- Returns:
- a GsonBuilder instance.
- Since:
- 2.8.3
-
excluder
@Deprecated public Excluder excluder()
Deprecated.This method by accident exposes an internal Gson class; it might be removed in a future version.
-
fieldNamingStrategy
public FieldNamingStrategy 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 withnullvalues, or just omits them.- See Also:
GsonBuilder.serializeNulls()
-
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:
GsonBuilder.disableHtmlEscaping()
-
doubleAdapter
private TypeAdapter<java.lang.Number> doubleAdapter(boolean serializeSpecialFloatingPointValues)
-
floatAdapter
private TypeAdapter<java.lang.Number> floatAdapter(boolean serializeSpecialFloatingPointValues)
-
checkValidFloatingPoint
static void checkValidFloatingPoint(double value)
-
longAdapter
private static TypeAdapter<java.lang.Number> longAdapter(LongSerializationPolicy longSerializationPolicy)
-
atomicLongAdapter
private static TypeAdapter<java.util.concurrent.atomic.AtomicLong> atomicLongAdapter(TypeAdapter<java.lang.Number> longAdapter)
-
atomicLongArrayAdapter
private static TypeAdapter<java.util.concurrent.atomic.AtomicLongArray> atomicLongArrayAdapter(TypeAdapter<java.lang.Number> longAdapter)
-
getAdapter
public <T> TypeAdapter<T> getAdapter(TypeToken<T> type)
Returns the type adapter fortype.When calling this method concurrently from multiple threads and requesting an adapter for the same type this method may return different
TypeAdapterinstances. However, that should normally not be an issue becauseTypeAdapterimplementations are supposed to be stateless.- Throws:
java.lang.IllegalArgumentException- if this Gson instance cannot serialize and deserializetype.
-
getAdapter
public <T> TypeAdapter<T> getAdapter(java.lang.Class<T> type)
Returns the type adapter fortype.- Throws:
java.lang.IllegalArgumentException- if this Gson instance cannot serialize and deserializetype.
-
getDelegateAdapter
public <T> TypeAdapter<T> getDelegateAdapter(TypeAdapterFactory skipPast, TypeToken<T> type)
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 aTypeAdapterFactorythat you may have registered. This feature 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
getDelegateAdaptermethod:
This factory can now be used like this:class StatsTypeAdapterFactory implements TypeAdapterFactory { public int numReads = 0; public int numWrites = 0; public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { 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); } }; } }
Note that this call will skip all factories registered beforeStatsTypeAdapterFactory 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 ensure 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 the type adapter factories for some types, seeGsonBuilder.registerTypeAdapter(Type, Object), our stats factory will not count the number of instances of those types that will be read or written.If
skipPastis a factory which has neither been registered on theGsonBuildernor specified with the@JsonAdapterannotation on a class, then this method behaves as ifgetAdapter(TypeToken)had been called. This also means that for fields with@JsonAdapterannotation this method behaves normally likegetAdapter(except for corner cases where a customInstanceCreatoris used to create an instance of the factory).- 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 wheregetDelegateAdaptermethod is being invoked).type- Type for which the delegate adapter is being searched for.- Since:
- 2.2
-
toJsonTree
public JsonElement toJsonTree(java.lang.Object src)
This method serializes the specified object into its equivalent representation as a tree ofJsonElements. 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 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- Returns:
- JSON representation of
src. - Since:
- 1.4
- See Also:
toJsonTree(Object, Type)
-
toJsonTree
public JsonElement toJsonTree(java.lang.Object src, java.lang.reflect.Type typeOfSrc)
This method serializes the specified object, including those of generic types, into its equivalent representation as a tree ofJsonElements. 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 theTypeTokenclass. 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
- See Also:
toJsonTree(Object)
-
toJson
public java.lang.String toJson(java.lang.Object src)
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 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- Returns:
- JSON representation of
src. - See Also:
toJson(Object, Appendable),toJson(Object, Type)
-
toJson
public java.lang.String toJson(java.lang.Object src, java.lang.reflect.Type typeOfSrc)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 theTypeTokenclass. For example, to get the type forCollection<Foo>, you should use:Type typeOfSrc = new TypeToken<Collection<Foo>>(){}.getType();- Returns:
- JSON representation of
src. - See Also:
toJson(Object, Type, Appendable),toJson(Object)
-
toJson
public void toJson(java.lang.Object src, java.lang.Appendable writer) throws JsonIOExceptionThis method serializes the specified object into its equivalent JSON representation and writes it to the writer. 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 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 createdwriter- Writer to which the JSON representation needs to be written- Throws:
JsonIOException- if there was a problem writing to the writer- Since:
- 1.2
- See Also:
toJson(Object),toJson(Object, Type, Appendable)
-
toJson
public void toJson(java.lang.Object src, java.lang.reflect.Type typeOfSrc, java.lang.Appendable writer) throws JsonIOExceptionThis method serializes the specified object, including those of generic types, into its equivalent JSON representation and writes it to the writer. 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 theTypeTokenclass. 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
- See Also:
toJson(Object, Type),toJson(Object, Appendable)
-
toJson
public void toJson(java.lang.Object src, java.lang.reflect.Type typeOfSrc, JsonWriter writer) throws JsonIOExceptionWrites the JSON representation ofsrcof typetypeOfSrctowriter.If the
Gsoninstance has an explicit strictness setting, this setting will be used for writing the JSON regardless of the strictness of the providedJsonWriter. For legacy reasons, if theGsoninstance has no explicit strictness setting and the writer does not have the strictnessStrictness.STRICT, the JSON will be written inStrictness.LENIENTmode.
Note that in all cases the old strictness setting of the writer will be restored when this method returns.The 'HTML-safe' and 'serialize
null' settings of thisGsoninstance (configured by theGsonBuilder) are applied, and the original settings of the writer are restored once this method returns.- Parameters:
src- the object for which JSON representation is to be createdtypeOfSrc- the type of the object to be writtenwriter- Writer to which the JSON representation of src needs to be written- Throws:
JsonIOException- if there was a problem writing to the writer
-
toJson
public java.lang.String toJson(JsonElement jsonElement)
Converts a tree ofJsonElements into its equivalent JSON representation.- Parameters:
jsonElement- root of a tree ofJsonElements- Returns:
- JSON String representation of the tree.
- Since:
- 1.4
-
toJson
public void toJson(JsonElement jsonElement, java.lang.Appendable writer) throws JsonIOException
Writes out the equivalent JSON for a tree ofJsonElements.- Parameters:
jsonElement- root of a tree ofJsonElementswriter- Writer to which the JSON representation needs to be written- Throws:
JsonIOException- if there was a problem writing to the writer- Since:
- 1.4
-
toJson
public void toJson(JsonElement jsonElement, JsonWriter writer) throws JsonIOException
Writes the JSON forjsonElementtowriter.If the
Gsoninstance has an explicit strictness setting, this setting will be used for writing the JSON regardless of the strictness of the providedJsonWriter. For legacy reasons, if theGsoninstance has no explicit strictness setting and the writer does not have the strictnessStrictness.STRICT, the JSON will be written inStrictness.LENIENTmode.
Note that in all cases the old strictness setting of the writer will be restored when this method returns.The 'HTML-safe' and 'serialize
null' settings of thisGsoninstance (configured by theGsonBuilder) are applied, and the original settings of the writer are restored once this method returns.- Parameters:
jsonElement- the JSON element to be writtenwriter- the JSON writer to which the provided element will be written- Throws:
JsonIOException- if there was a problem writing to the writer
-
newJsonWriter
public JsonWriter newJsonWriter(java.io.Writer writer) throws java.io.IOException
Returns a new JSON writer configured for the settings on this Gson instance.The following settings are considered:
GsonBuilder.disableHtmlEscaping()GsonBuilder.generateNonExecutableJson()GsonBuilder.serializeNulls()GsonBuilder.setStrictness(Strictness). If no explicit strictness has been set the created writer will have a strictness ofStrictness.LEGACY_STRICT. Otherwise, the strictness of theGsoninstance will be used for the created writer.GsonBuilder.setPrettyPrinting()GsonBuilder.setFormattingStyle(FormattingStyle)
- Throws:
java.io.IOException
-
newJsonReader
public JsonReader newJsonReader(java.io.Reader reader)
Returns a new JSON reader configured for the settings on this Gson instance.The following settings are considered:
GsonBuilder.setStrictness(Strictness). If no explicit strictness has been set the created reader will have a strictness ofStrictness.LEGACY_STRICT. Otherwise, the strictness of theGsoninstance will be used for the created reader.
-
fromJson
public <T> T fromJson(java.lang.String json, java.lang.Class<T> classOfT) throws JsonSyntaxExceptionThis 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 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, TypeToken). If you have the JSON in aReaderinstead of a String, usefromJson(Reader, Class)instead.An exception is thrown if the JSON string has multiple top-level JSON elements, or if there is trailing data. Use
fromJson(JsonReader, Type)if this behavior is not desired.- 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
nullifjsonisnullor ifjsonis empty. - Throws:
JsonSyntaxException- if json is not a valid representation for an object of type classOfT- See Also:
fromJson(Reader, Class),fromJson(String, TypeToken)
-
fromJson
public <T> T fromJson(java.lang.String json, java.lang.reflect.Type typeOfT) throws JsonSyntaxExceptionThis 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 aReaderinstead of a String, usefromJson(Reader, Type)instead.Since
Typeis not parameterized by T, this method is not type-safe and should be used carefully. If you are creating theTypefrom aTypeToken, prefer usingfromJson(String, TypeToken)instead since its return type is based on theTypeTokenand is therefore more type-safe.An exception is thrown if the JSON string has multiple top-level JSON elements, or if there is trailing data. Use
fromJson(JsonReader, Type)if this behavior is not desired.- 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- Returns:
- an object of type T from the string. Returns
nullifjsonisnullor ifjsonis empty. - Throws:
JsonSyntaxException- if json is not a valid representation for an object of type typeOfT- See Also:
fromJson(Reader, Type),fromJson(String, Class),fromJson(String, TypeToken)
-
fromJson
public <T> T fromJson(java.lang.String json, TypeToken<T> typeOfT) throws JsonSyntaxExceptionThis 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 aReaderinstead of a String, usefromJson(Reader, TypeToken)instead.An exception is thrown if the JSON string has multiple top-level JSON elements, or if there is trailing data. Use
fromJson(JsonReader, TypeToken)if this behavior is not desired.- 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 should create an anonymous subclass ofTypeTokenwith the specific generic type arguments. For example, to get the type forCollection<Foo>, you should use:new TypeToken<Collection<Foo>>(){}- Returns:
- an object of type T from the string. Returns
nullifjsonisnullor ifjsonis empty. - Throws:
JsonSyntaxException- if json is not a valid representation for an object of the type typeOfT- Since:
- 2.10
- See Also:
fromJson(Reader, TypeToken),fromJson(String, Class)
-
fromJson
public <T> T fromJson(java.io.Reader json, java.lang.Class<T> classOfT) throws JsonSyntaxException, JsonIOExceptionThis 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 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, TypeToken). If you have the JSON in a String form instead of aReader, usefromJson(String, Class)instead.An exception is thrown if the JSON data has multiple top-level JSON elements, or if there is trailing data. Use
fromJson(JsonReader, Type)if this behavior is not desired.- 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 Reader. Returns
nullifjsonis 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 typeOfT- Since:
- 1.2
- See Also:
fromJson(String, Class),fromJson(Reader, TypeToken)
-
fromJson
public <T> T fromJson(java.io.Reader json, java.lang.reflect.Type typeOfT) throws JsonIOException, JsonSyntaxExceptionThis 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.Since
Typeis not parameterized by T, this method is not type-safe and should be used carefully. If you are creating theTypefrom aTypeToken, prefer usingfromJson(Reader, TypeToken)instead since its return type is based on theTypeTokenand is therefore more type-safe.An exception is thrown if the JSON data has multiple top-level JSON elements, or if there is trailing data. Use
fromJson(JsonReader, Type)if this behavior is not desired.- 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- Returns:
- an object of type T from the Reader. Returns
nullifjsonis 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 typeOfT- Since:
- 1.2
- See Also:
fromJson(String, Type),fromJson(Reader, Class),fromJson(Reader, TypeToken)
-
fromJson
public <T> T fromJson(java.io.Reader json, TypeToken<T> typeOfT) throws JsonIOException, JsonSyntaxExceptionThis 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, TypeToken)instead.An exception is thrown if the JSON data has multiple top-level JSON elements, or if there is trailing data. Use
fromJson(JsonReader, TypeToken)if this behavior is not desired.- 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 should create an anonymous subclass ofTypeTokenwith the specific generic type arguments. For example, to get the type forCollection<Foo>, you should use:new TypeToken<Collection<Foo>>(){}- Returns:
- an object of type T from the Reader. Returns
nullifjsonis 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 of typeOfT- Since:
- 2.10
- See Also:
fromJson(String, TypeToken),fromJson(Reader, Class)
-
fromJson
public <T> T fromJson(JsonReader reader, java.lang.reflect.Type typeOfT) throws JsonIOException, JsonSyntaxException
Reads the next JSON value fromreaderand converts it to an object of typetypeOfT. Returnsnull, if thereaderis at EOF.Since
Typeis not parameterized by T, this method is not type-safe and should be used carefully. If you are creating theTypefrom aTypeToken, prefer usingfromJson(JsonReader, TypeToken)instead since its return type is based on theTypeTokenand is therefore more type-safe. If the provided type is aClasstheTypeTokencan be created withTypeToken.get(Class).Unlike the other
fromJsonmethods, no exception is thrown if the JSON data has multiple top-level JSON elements, or if there is trailing data.If the
Gsoninstance has an explicit strictness setting, this setting will be used for reading the JSON regardless of the strictness of the providedJsonReader. For legacy reasons, if theGsoninstance has no explicit strictness setting and the reader does not have the strictnessStrictness.STRICT, the JSON will be written inStrictness.LENIENTmode.
Note that in all cases the old strictness setting of the reader will be restored when this method returns.- Type Parameters:
T- the type of the desired object- Parameters:
reader- the reader whose next JSON value should be deserializedtypeOfT- The specific genericized type of src- Returns:
- an object of type T from the JsonReader. Returns
nullifreaderis at EOF. - Throws:
JsonIOException- if there was a problem reading from the JsonReaderJsonSyntaxException- if json is not a valid representation for an object of type typeOfT- See Also:
fromJson(Reader, Type),fromJson(JsonReader, TypeToken)
-
fromJson
public <T> T fromJson(JsonReader reader, TypeToken<T> typeOfT) throws JsonIOException, JsonSyntaxException
Reads the next JSON value fromreaderand converts it to an object of typetypeOfT. Returnsnull, if thereaderis at EOF. This method is useful if the specified object is a generic type. For non-generic objects,fromJson(JsonReader, Type)can be called, orTypeToken.get(Class)can be used to create the type token.Unlike the other
fromJsonmethods, no exception is thrown if the JSON data has multiple top-level JSON elements, or if there is trailing data.If the
Gsoninstance has an explicit strictness setting, this setting will be used for reading the JSON regardless of the strictness of the providedJsonReader. For legacy reasons, if theGsoninstance has no explicit strictness setting and the reader does not have the strictnessStrictness.STRICT, the JSON will be written inStrictness.LENIENTmode.
Note that in all cases the old strictness setting of the reader will be restored when this method returns.- Type Parameters:
T- the type of the desired object- Parameters:
reader- the reader whose next JSON value should be deserializedtypeOfT- The specific genericized type of src. You should create an anonymous subclass ofTypeTokenwith the specific generic type arguments. For example, to get the type forCollection<Foo>, you should use:new TypeToken<Collection<Foo>>(){}- Returns:
- an object of type T from the JsonReader. Returns
nullifreaderis at EOF. - Throws:
JsonIOException- if there was a problem reading from the JsonReaderJsonSyntaxException- if json is not a valid representation for an object of the type typeOfT- Since:
- 2.10
- See Also:
fromJson(Reader, TypeToken),fromJson(JsonReader, Type)
-
fromJson
public <T> T fromJson(JsonElement json, java.lang.Class<T> classOfT) throws JsonSyntaxException
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 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, TypeToken).- Type Parameters:
T- the type of the desired object- Parameters:
json- the root of the parse tree ofJsonElements from which the object is to be deserializedclassOfT- The class of T- Returns:
- an object of type T from the JSON. Returns
nullifjsonisnullor ifjsonis empty. - Throws:
JsonSyntaxException- if json is not a valid representation for an object of type classOfT- Since:
- 1.3
- See Also:
fromJson(Reader, Class),fromJson(JsonElement, TypeToken)
-
fromJson
public <T> T fromJson(JsonElement json, java.lang.reflect.Type typeOfT) throws JsonSyntaxException
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.Since
Typeis not parameterized by T, this method is not type-safe and should be used carefully. If you are creating theTypefrom aTypeToken, prefer usingfromJson(JsonElement, TypeToken)instead since its return type is based on theTypeTokenand is therefore more type-safe.- Type Parameters:
T- the type of the desired object- Parameters:
json- the root of the parse tree ofJsonElements from which the object is to be deserializedtypeOfT- The specific genericized type of src- Returns:
- an object of type T from the JSON. Returns
nullifjsonisnullor ifjsonis empty. - Throws:
JsonSyntaxException- if json is not a valid representation for an object of type typeOfT- Since:
- 1.3
- See Also:
fromJson(Reader, Type),fromJson(JsonElement, Class),fromJson(JsonElement, TypeToken)
-
fromJson
public <T> T fromJson(JsonElement json, TypeToken<T> typeOfT) throws JsonSyntaxException
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 ofJsonElements from which the object is to be deserializedtypeOfT- The specific genericized type of src. You should create an anonymous subclass ofTypeTokenwith the specific generic type arguments. For example, to get the type forCollection<Foo>, you should use:new TypeToken<Collection<Foo>>(){}- Returns:
- an object of type T from the JSON. Returns
nullifjsonisnullor ifjsonis empty. - Throws:
JsonSyntaxException- if json is not a valid representation for an object of type typeOfT- Since:
- 2.10
- See Also:
fromJson(Reader, TypeToken),fromJson(JsonElement, Class)
-
assertFullConsumption
private static void assertFullConsumption(java.lang.Object obj, JsonReader reader)
-
toString
public java.lang.String toString()
- Overrides:
toStringin classjava.lang.Object
-
-