Class Gson

java.lang.Object
com.google.gson.Gson

public final class Gson extends Object
This is the main class for using Gson. Gson is typically used by first constructing a Gson instance and then invoking 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 newline, custom indent, custom JsonSerializers, JsonDeserializers, and InstanceCreators.

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 example List<MyType>) then for deserialization you must use a fromJson method with Type or TypeToken parameter to specify the parameterized type. For serialization specifying a Type or TypeToken is optional, otherwise Gson will use the runtime type of the object. TypeToken is 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 the Gson methods allow JSON data which does not comply with the JSON specification when no explicit strictness is set (the default). To specify the strictness of a Gson instance, you should set it through GsonBuilder.setStrictness(Strictness).

For older Gson versions, which don't have the strictness mode API, the following workarounds can be used:

Serialization

  1. Use getAdapter(Class) to obtain the adapter for the type to be serialized
  2. When using an existing JsonWriter, manually apply the writer settings of this Gson instance listed by newJsonWriter(Writer).
    Otherwise, when not using an existing JsonWriter, use newJsonWriter(Writer) to construct one.
  3. Call TypeAdapter.write(JsonWriter, Object)

Deserialization

  1. Use getAdapter(Class) to obtain the adapter for the type to be deserialized
  2. When using an existing JsonReader, manually apply the reader settings of this Gson instance listed by newJsonReader(Reader).
    Otherwise, when not using an existing JsonReader, use newJsonReader(Reader) to construct one.
  3. Call TypeAdapter.read(JsonReader)
  4. Call JsonReader.peek() and verify that the result is JsonToken.END_DOCUMENT to make sure there is no trailing data
Note that the JsonReader created this way is only 'legacy strict', it mostly adheres to the JSON specification but allows small deviations. See JsonReader.setStrictness(Strictness) for details.
See Also:
  • Field Details

    • DEFAULT_JSON_NON_EXECUTABLE

      static final boolean DEFAULT_JSON_NON_EXECUTABLE
      See Also:
    • 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:
    • 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:
    • DEFAULT_USE_JDK_UNSAFE

      static final boolean DEFAULT_USE_JDK_UNSAFE
      See Also:
    • DEFAULT_DATE_PATTERN

      static final 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 String JSON_NON_EXECUTABLE_PREFIX
      See Also:
    • threadLocalAdapterResults

      private final ThreadLocal<Map<TypeToken<?>,TypeAdapter<?>>> threadLocalAdapterResults
      This thread local guards against reentrant calls to getAdapter(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 getAdapter calls, with the type token provided to getAdapter as key and either FutureTypeAdapter or a regular TypeAdapter as value.

    • typeTokenCache

      private final ConcurrentMap<TypeToken<?>,TypeAdapter<?>> typeTokenCache
    • constructorConstructor

      private final ConstructorConstructor constructorConstructor
    • jsonAdapterFactory

      private final JsonAdapterAnnotationTypeAdapterFactory jsonAdapterFactory
    • factories

      final List<TypeAdapterFactory> factories
    • excluder

      final Excluder excluder
    • fieldNamingStrategy

      final FieldNamingStrategy fieldNamingStrategy
    • instanceCreators

      final Map<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 String datePattern
    • dateStyle

      final int dateStyle
    • timeStyle

      final int timeStyle
    • longSerializationPolicy

      final LongSerializationPolicy longSerializationPolicy
    • builderFactories

      final List<TypeAdapterFactory> builderFactories
    • builderHierarchyFactories

      final List<TypeAdapterFactory> builderHierarchyFactories
    • objectToNumberStrategy

      final ToNumberStrategy objectToNumberStrategy
    • numberToNumberStrategy

      final ToNumberStrategy numberToNumberStrategy
    • reflectionFilters

      final List<ReflectionAccessFilter> reflectionFilters
  • Constructor Details

  • Method Details

    • 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.
      See Also:
    • serializeNulls

      public boolean serializeNulls()
      Returns whether this Gson instance is serializing JSON object properties with null 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

      private TypeAdapter<Number> doubleAdapter(boolean serializeSpecialFloatingPointValues)
    • floatAdapter

      private TypeAdapter<Number> floatAdapter(boolean serializeSpecialFloatingPointValues)
    • checkValidFloatingPoint

      static void checkValidFloatingPoint(double value)
    • longAdapter

      private static TypeAdapter<Number> longAdapter(LongSerializationPolicy longSerializationPolicy)
    • atomicLongAdapter

      private static TypeAdapter<AtomicLong> atomicLongAdapter(TypeAdapter<Number> longAdapter)
    • atomicLongArrayAdapter

      private static TypeAdapter<AtomicLongArray> atomicLongArrayAdapter(TypeAdapter<Number> longAdapter)
    • getAdapter

      public <T> TypeAdapter<T> getAdapter(TypeToken<T> type)
      Returns the type adapter for type.

      When calling this method concurrently from multiple threads and requesting an adapter for the same type this method may return different TypeAdapter instances. However, that should normally not be an issue because TypeAdapter implementations are supposed to be stateless.

      Throws:
      IllegalArgumentException - if this Gson instance cannot serialize and deserialize type.
    • getAdapter

      public <T> TypeAdapter<T> getAdapter(Class<T> type)
      Returns the type adapter for type.
      Throws:
      IllegalArgumentException - if this Gson instance cannot serialize and deserialize type.
    • 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 a TypeAdapterFactory that 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 getDelegateAdapter method:

      
       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);
             }
           };
         }
       }
       
      This factory can now be used like this:
      
       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);
       
      Note that this call will skip all factories registered before 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, see GsonBuilder.registerTypeAdapter(Type, Object), our stats factory will not count the number of instances of those types that will be read or written.

      If skipPast is a factory which has neither been registered on the GsonBuilder nor specified with the @JsonAdapter annotation on a class, then this method behaves as if getAdapter(TypeToken) had been called. This also means that for fields with @JsonAdapter annotation this method behaves normally like getAdapter (except for corner cases where a custom InstanceCreator is 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 where getDelegateAdapter method is being invoked).
      type - Type for which the delegate adapter is being searched for.
      Since:
      2.2
    • toJsonTree

      public JsonElement toJsonTree(Object src)
      This method serializes the specified object into its equivalent representation as a tree of JsonElements. This method should be used when the specified object is not a generic type. This method uses Object.getClass() to get the type for the specified object, but the getClass() 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, use toJsonTree(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

      public JsonElement toJsonTree(Object src, Type typeOfSrc)
      This method serializes the specified object, including those of generic types, into its equivalent representation as a tree of JsonElements. This method must be used if the specified object is a generic type. For non-generic objects, use toJsonTree(Object) instead.
      Parameters:
      src - the object for which JSON representation is to be created
      typeOfSrc - The specific genericized type of src. You can obtain this type by using the TypeToken class. For example, to get the type for Collection<Foo>, you should use:
       Type typeOfSrc = new TypeToken<Collection<Foo>>(){}.getType();
       
      Returns:
      JSON representation of src.
      Since:
      1.4
      See Also:
    • toJson

      public String toJson(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 uses Object.getClass() to get the type for the specified object, but the getClass() 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, use toJson(Object, Type) instead. If you want to write out the object to a Writer, use toJson(Object, Appendable) instead.
      Parameters:
      src - the object for which JSON representation is to be created
      Returns:
      JSON representation of src.
      See Also:
    • toJson

      public String toJson(Object src, 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, use toJson(Object) instead. If you want to write out the object to a Appendable, use toJson(Object, Type, Appendable) instead.
      Parameters:
      src - the object for which JSON representation is to be created
      typeOfSrc - The specific genericized type of src. You can obtain this type by using the TypeToken class. For example, to get the type for Collection<Foo>, you should use:
       Type typeOfSrc = new TypeToken<Collection<Foo>>(){}.getType();
       
      Returns:
      JSON representation of src.
      See Also:
    • toJson

      public void toJson(Object src, Appendable writer) throws JsonIOException
      This 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 uses Object.getClass() to get the type for the specified object, but the getClass() 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, use toJson(Object, Type, Appendable) instead.
      Parameters:
      src - the object for which JSON representation is to be created
      writer - 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

      public void toJson(Object src, Type typeOfSrc, Appendable writer) throws JsonIOException
      This 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, use toJson(Object, Appendable) instead.
      Parameters:
      src - the object for which JSON representation is to be created
      typeOfSrc - The specific genericized type of src. You can obtain this type by using the TypeToken class. For example, to get the type for Collection<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

      public void toJson(Object src, Type typeOfSrc, JsonWriter writer) throws JsonIOException
      Writes the JSON representation of src of type typeOfSrc to writer.

      If the Gson instance has an explicit strictness setting, this setting will be used for writing the JSON regardless of the strictness of the provided JsonWriter. For legacy reasons, if the Gson instance has no explicit strictness setting and the writer does not have the strictness Strictness.STRICT, the JSON will be written in Strictness.LENIENT mode.
      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 this Gson instance (configured by the GsonBuilder) 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 created
      typeOfSrc - the type of the object to be written
      writer - 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 String toJson(JsonElement jsonElement)
      Converts a tree of JsonElements into its equivalent JSON representation.
      Parameters:
      jsonElement - root of a tree of JsonElements
      Returns:
      JSON String representation of the tree.
      Since:
      1.4
    • toJson

      public void toJson(JsonElement jsonElement, Appendable writer) throws JsonIOException
      Writes out the equivalent JSON for a tree of JsonElements.
      Parameters:
      jsonElement - root of a tree of JsonElements
      writer - 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 for jsonElement to writer.

      If the Gson instance has an explicit strictness setting, this setting will be used for writing the JSON regardless of the strictness of the provided JsonWriter. For legacy reasons, if the Gson instance has no explicit strictness setting and the writer does not have the strictness Strictness.STRICT, the JSON will be written in Strictness.LENIENT mode.
      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 this Gson instance (configured by the GsonBuilder) are applied, and the original settings of the writer are restored once this method returns.

      Parameters:
      jsonElement - the JSON element to be written
      writer - 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(Writer writer) throws IOException
      Returns a new JSON writer configured for the settings on this Gson instance.

      The following settings are considered:

      Throws:
      IOException
    • newJsonReader

      public JsonReader newJsonReader(Reader reader)
      Returns a new JSON reader configured for the settings on this Gson instance.

      The following settings are considered:

    • fromJson

      public <T> T fromJson(String json, Class<T> classOfT) throws JsonSyntaxException
      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 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, invoke fromJson(String, TypeToken). If you have the JSON in a Reader instead of a String, use fromJson(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 deserialized
      classOfT - the class of T
      Returns:
      an object of type T from the string. Returns null if json is null or if json is empty.
      Throws:
      JsonSyntaxException - if json is not a valid representation for an object of type classOfT
      See Also:
    • fromJson

      public <T> T fromJson(String json, Type typeOfT) throws JsonSyntaxException
      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, use fromJson(String, Class) instead. If you have the JSON in a Reader instead of a String, use fromJson(Reader, Type) instead.

      Since Type is not parameterized by T, this method is not type-safe and should be used carefully. If you are creating the Type from a TypeToken, prefer using fromJson(String, TypeToken) instead since its return type is based on the TypeToken and 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 deserialized
      typeOfT - The specific genericized type of src
      Returns:
      an object of type T from the string. Returns null if json is null or if json is empty.
      Throws:
      JsonSyntaxException - if json is not a valid representation for an object of type typeOfT
      See Also:
    • fromJson

      public <T> T fromJson(String json, TypeToken<T> typeOfT) throws JsonSyntaxException
      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, use fromJson(String, Class) instead. If you have the JSON in a Reader instead of a String, use fromJson(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 deserialized
      typeOfT - The specific genericized type of src. You should create an anonymous subclass of TypeToken with the specific generic type arguments. For example, to get the type for Collection<Foo>, you should use:
       new TypeToken<Collection<Foo>>(){}
       
      Returns:
      an object of type T from the string. Returns null if json is null or if json is empty.
      Throws:
      JsonSyntaxException - if json is not a valid representation for an object of the type typeOfT
      Since:
      2.10
      See Also:
    • fromJson

      public <T> T fromJson(Reader json, Class<T> classOfT) throws JsonSyntaxException, JsonIOException
      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 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, invoke fromJson(Reader, TypeToken). If you have the JSON in a String form instead of a Reader, use fromJson(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 null if json is at EOF.
      Throws:
      JsonIOException - if there was a problem reading from the Reader
      JsonSyntaxException - if json is not a valid representation for an object of type typeOfT
      Since:
      1.2
      See Also:
    • fromJson

      public <T> T fromJson(Reader json, Type typeOfT) throws JsonIOException, JsonSyntaxException
      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, use fromJson(Reader, Class) instead. If you have the JSON in a String form instead of a Reader, use fromJson(String, Type) instead.

      Since Type is not parameterized by T, this method is not type-safe and should be used carefully. If you are creating the Type from a TypeToken, prefer using fromJson(Reader, TypeToken) instead since its return type is based on the TypeToken and 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 deserialized
      typeOfT - The specific genericized type of src
      Returns:
      an object of type T from the Reader. Returns null if json is at EOF.
      Throws:
      JsonIOException - if there was a problem reading from the Reader
      JsonSyntaxException - if json is not a valid representation for an object of type typeOfT
      Since:
      1.2
      See Also:
    • fromJson

      public <T> T fromJson(Reader json, TypeToken<T> typeOfT) throws JsonIOException, JsonSyntaxException
      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, use fromJson(Reader, Class) instead. If you have the JSON in a String form instead of a Reader, use fromJson(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 deserialized
      typeOfT - The specific genericized type of src. You should create an anonymous subclass of TypeToken with the specific generic type arguments. For example, to get the type for Collection<Foo>, you should use:
       new TypeToken<Collection<Foo>>(){}
       
      Returns:
      an object of type T from the Reader. Returns null if json is at EOF.
      Throws:
      JsonIOException - if there was a problem reading from the Reader
      JsonSyntaxException - if json is not a valid representation for an object of type of typeOfT
      Since:
      2.10
      See Also:
    • fromJson

      public <T> T fromJson(JsonReader reader, Type typeOfT) throws JsonIOException, JsonSyntaxException
      Reads the next JSON value from reader and converts it to an object of type typeOfT. Returns null, if the reader is at EOF.

      Since Type is not parameterized by T, this method is not type-safe and should be used carefully. If you are creating the Type from a TypeToken, prefer using fromJson(JsonReader, TypeToken) instead since its return type is based on the TypeToken and is therefore more type-safe. If the provided type is a Class the TypeToken can be created with TypeToken.get(Class).

      Unlike the other fromJson methods, no exception is thrown if the JSON data has multiple top-level JSON elements, or if there is trailing data.

      If the Gson instance has an explicit strictness setting, this setting will be used for reading the JSON regardless of the strictness of the provided JsonReader. For legacy reasons, if the Gson instance has no explicit strictness setting and the reader does not have the strictness Strictness.STRICT, the JSON will be written in Strictness.LENIENT mode.
      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 deserialized
      typeOfT - The specific genericized type of src
      Returns:
      an object of type T from the JsonReader. Returns null if reader is at EOF.
      Throws:
      JsonIOException - if there was a problem reading from the JsonReader
      JsonSyntaxException - if json is not a valid representation for an object of type typeOfT
      See Also:
    • fromJson

      public <T> T fromJson(JsonReader reader, TypeToken<T> typeOfT) throws JsonIOException, JsonSyntaxException
      Reads the next JSON value from reader and converts it to an object of type typeOfT. Returns null, if the reader is at EOF. This method is useful if the specified object is a generic type. For non-generic objects, fromJson(JsonReader, Type) can be called, or TypeToken.get(Class) can be used to create the type token.

      Unlike the other fromJson methods, no exception is thrown if the JSON data has multiple top-level JSON elements, or if there is trailing data.

      If the Gson instance has an explicit strictness setting, this setting will be used for reading the JSON regardless of the strictness of the provided JsonReader. For legacy reasons, if the Gson instance has no explicit strictness setting and the reader does not have the strictness Strictness.STRICT, the JSON will be written in Strictness.LENIENT mode.
      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 deserialized
      typeOfT - The specific genericized type of src. You should create an anonymous subclass of TypeToken with the specific generic type arguments. For example, to get the type for Collection<Foo>, you should use:
       new TypeToken<Collection<Foo>>(){}
       
      Returns:
      an object of type T from the JsonReader. Returns null if reader is at EOF.
      Throws:
      JsonIOException - if there was a problem reading from the JsonReader
      JsonSyntaxException - if json is not a valid representation for an object of the type typeOfT
      Since:
      2.10
      See Also:
    • fromJson

      public <T> T fromJson(JsonElement json, 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, invoke fromJson(JsonElement, TypeToken).
      Type Parameters:
      T - the type of the desired object
      Parameters:
      json - the root of the parse tree of JsonElements from which the object is to be deserialized
      classOfT - The class of T
      Returns:
      an object of type T from the JSON. Returns null if json is null or if json is empty.
      Throws:
      JsonSyntaxException - if json is not a valid representation for an object of type classOfT
      Since:
      1.3
      See Also:
    • fromJson

      public <T> T fromJson(JsonElement json, 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, use fromJson(JsonElement, Class) instead.

      Since Type is not parameterized by T, this method is not type-safe and should be used carefully. If you are creating the Type from a TypeToken, prefer using fromJson(JsonElement, TypeToken) instead since its return type is based on the TypeToken and is therefore more type-safe.

      Type Parameters:
      T - the type of the desired object
      Parameters:
      json - the root of the parse tree of JsonElements from which the object is to be deserialized
      typeOfT - The specific genericized type of src
      Returns:
      an object of type T from the JSON. Returns null if json is null or if json is empty.
      Throws:
      JsonSyntaxException - if json is not a valid representation for an object of type typeOfT
      Since:
      1.3
      See Also:
    • 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, use fromJson(JsonElement, Class) instead.
      Type Parameters:
      T - the type of the desired object
      Parameters:
      json - the root of the parse tree of JsonElements from which the object is to be deserialized
      typeOfT - The specific genericized type of src. You should create an anonymous subclass of TypeToken with the specific generic type arguments. For example, to get the type for Collection<Foo>, you should use:
       new TypeToken<Collection<Foo>>(){}
       
      Returns:
      an object of type T from the JSON. Returns null if json is null or if json is empty.
      Throws:
      JsonSyntaxException - if json is not a valid representation for an object of type typeOfT
      Since:
      2.10
      See Also:
    • assertFullConsumption

      private static void assertFullConsumption(Object obj, JsonReader reader)
    • toString

      public String toString()
      Overrides:
      toString in class Object