public final class Gson
extends java.lang.Object
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.
TypeToken
Constructor and Description |
---|
Gson()
Constructs a Gson object with default configuration.
|
Modifier and Type | Method and Description |
---|---|
com.google.gson.internal.Excluder |
excluder() |
FieldNamingStrategy |
fieldNamingStrategy() |
<T> T |
fromJson(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> T |
fromJson(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> T |
fromJson(JsonReader reader,
java.lang.reflect.Type typeOfT)
Reads the next JSON value from
reader and convert it to an object
of type typeOfT . |
<T> T |
fromJson(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> T |
fromJson(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> T |
fromJson(java.lang.String json,
java.lang.Class<T> classOfT)
This method deserializes the specified Json into an object of the specified class.
|
<T> T |
fromJson(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(java.lang.Class<T> type)
Returns the type adapter for type.
|
<T> TypeAdapter<T> |
getAdapter(TypeToken<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() |
JsonReader |
newJsonReader(java.io.Reader reader)
Returns a new JSON reader configured for the settings on this Gson instance.
|
JsonWriter |
newJsonWriter(java.io.Writer writer)
Returns a new JSON writer configured for the settings on this Gson instance.
|
boolean |
serializeNulls() |
java.lang.String |
toJson(JsonElement jsonElement)
Converts a tree of
JsonElement s into its equivalent JSON representation. |
void |
toJson(JsonElement jsonElement,
java.lang.Appendable writer)
Writes out the equivalent JSON for a tree of
JsonElement s. |
void |
toJson(JsonElement jsonElement,
JsonWriter writer)
Writes the JSON for
jsonElement to writer . |
java.lang.String |
toJson(java.lang.Object src)
This method serializes the specified object into its equivalent Json representation.
|
void |
toJson(java.lang.Object src,
java.lang.Appendable writer)
This method serializes the specified object into its equivalent Json representation.
|
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.
|
void |
toJson(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.
|
void |
toJson(java.lang.Object src,
java.lang.reflect.Type typeOfSrc,
JsonWriter writer)
Writes the JSON representation of
src of type typeOfSrc to
writer . |
JsonElement |
toJsonTree(java.lang.Object src)
This method serializes the specified object into its equivalent representation as a tree of
JsonElement s. |
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 of
JsonElement s. |
java.lang.String |
toString() |
public Gson()
toJson
methods is in compact representation. This
means that all the unneeded white-space is removed. You can change this behavior with
GsonBuilder.setPrettyPrinting()
. GsonBuilder.serializeNulls()
.Map
,
URL
, URI
, Locale
, Date
,
BigDecimal
, and BigInteger
classes. If you would prefer
to change the default representation, you can do so by registering a type adapter through
GsonBuilder.registerTypeAdapter(Type, Object)
. DateFormat.DEFAULT
. This format
ignores the millisecond portion of the date during serialization. You can change
this by invoking GsonBuilder.setDateFormat(int)
or
GsonBuilder.setDateFormat(String)
. Expose
annotation.
You can enable Gson to serialize/deserialize only those fields marked with this annotation
through GsonBuilder.excludeFieldsWithoutExposeAnnotation()
. Since
annotation. You
can enable Gson to use this annotation through GsonBuilder.setVersion(double)
.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 through GsonBuilder.setFieldNamingPolicy(FieldNamingPolicy)
.transient
or static
fields from
consideration for serialization and deserialization. You can change this behavior through
GsonBuilder.excludeFieldsWithModifiers(int...)
.public com.google.gson.internal.Excluder excluder()
public FieldNamingStrategy fieldNamingStrategy()
public boolean serializeNulls()
public boolean htmlSafe()
public <T> TypeAdapter<T> getAdapter(TypeToken<T> type)
java.lang.IllegalArgumentException
- if this GSON cannot serialize and
deserialize type
.public <T> TypeAdapter<T> getDelegateAdapter(TypeAdapterFactory skipPast, TypeToken<T> type)
TypeAdapterFactory
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);
}
};
}
}
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 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.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(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.public <T> TypeAdapter<T> getAdapter(java.lang.Class<T> type)
java.lang.IllegalArgumentException
- if this GSON cannot serialize and
deserialize type
.public JsonElement toJsonTree(java.lang.Object src)
JsonElement
s. 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 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, use
toJsonTree(Object, Type)
instead.src
- the object for which Json representation is to be created setting for Gsonsrc
.public JsonElement toJsonTree(java.lang.Object src, java.lang.reflect.Type typeOfSrc)
JsonElement
s. This method must be used if the
specified object is a generic type. For non-generic objects, use toJsonTree(Object)
instead.src
- the object for which JSON representation is to be createdtypeOfSrc
- 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();
src
public java.lang.String toJson(java.lang.Object src)
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 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, use
toJson(Object, Type)
instead. If you want to write out the object to a
Writer
, use toJson(Object, Appendable)
instead.src
- the object for which Json representation is to be created setting for Gsonsrc
.public java.lang.String toJson(java.lang.Object src, java.lang.reflect.Type typeOfSrc)
toJson(Object)
instead. If you want to write out
the object to a Appendable
, use toJson(Object, Type, Appendable)
instead.src
- the object for which JSON representation is to be createdtypeOfSrc
- 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();
src
public void toJson(java.lang.Object src, java.lang.Appendable writer) throws JsonIOException
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 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, use
toJson(Object, Type, Appendable)
instead.src
- the object for which Json representation is to be created setting for Gsonwriter
- Writer to which the Json representation needs to be writtenJsonIOException
- if there was a problem writing to the writerpublic void toJson(java.lang.Object src, java.lang.reflect.Type typeOfSrc, java.lang.Appendable writer) throws JsonIOException
toJson(Object, Appendable)
instead.src
- the object for which JSON representation is to be createdtypeOfSrc
- 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.JsonIOException
- if there was a problem writing to the writerpublic void toJson(java.lang.Object src, java.lang.reflect.Type typeOfSrc, JsonWriter writer) throws JsonIOException
src
of type typeOfSrc
to
writer
.JsonIOException
- if there was a problem writing to the writerpublic java.lang.String toJson(JsonElement jsonElement)
JsonElement
s into its equivalent JSON representation.jsonElement
- root of a tree of JsonElement
spublic void toJson(JsonElement jsonElement, java.lang.Appendable writer) throws JsonIOException
JsonElement
s.jsonElement
- root of a tree of JsonElement
swriter
- Writer to which the Json representation needs to be writtenJsonIOException
- if there was a problem writing to the writerpublic JsonWriter newJsonWriter(java.io.Writer writer) throws java.io.IOException
java.io.IOException
public JsonReader newJsonReader(java.io.Reader reader)
public void toJson(JsonElement jsonElement, JsonWriter writer) throws JsonIOException
jsonElement
to writer
.JsonIOException
- if there was a problem writing to the writerpublic <T> T fromJson(java.lang.String json, java.lang.Class<T> classOfT) throws JsonSyntaxException
fromJson(String, Type)
. If you have the Json in a Reader
instead of
a String, use fromJson(Reader, Class)
instead.T
- the type of the desired objectjson
- the string from which the object is to be deserializedclassOfT
- the class of Tnull
if json
is null
or if json
is empty.JsonSyntaxException
- if json is not a valid representation for an object of type
classOfTpublic <T> T fromJson(java.lang.String json, java.lang.reflect.Type typeOfT) throws JsonSyntaxException
fromJson(String, Class)
instead. If you have the Json in a Reader
instead of
a String, use fromJson(Reader, Type)
instead.T
- the type of the desired objectjson
- the string from which the object is to be deserializedtypeOfT
- 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 typeOfT = new TypeToken<Collection<Foo>>(){}.getType();
null
if json
is null
.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 typepublic <T> T fromJson(java.io.Reader json, java.lang.Class<T> classOfT) throws JsonSyntaxException, JsonIOException
fromJson(Reader, Type)
. If you have the Json in a String form instead of a
Reader
, use fromJson(String, Class)
instead.T
- the type of the desired objectjson
- the reader producing the Json from which the object is to be deserialized.classOfT
- the class of Tnull
if json
is at EOF.JsonIOException
- if there was a problem reading from the ReaderJsonSyntaxException
- if json is not a valid representation for an object of typepublic <T> T fromJson(java.io.Reader json, java.lang.reflect.Type typeOfT) throws JsonIOException, JsonSyntaxException
fromJson(Reader, Class)
instead. If you have the Json in a
String form instead of a Reader
, use fromJson(String, Type)
instead.T
- the type of the desired objectjson
- 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 the
TypeToken
class. For example, to get the type for
Collection<Foo>
, you should use:
Type typeOfT = new TypeToken<Collection<Foo>>(){}.getType();
null
if json
is at EOF.JsonIOException
- if there was a problem reading from the ReaderJsonSyntaxException
- if json is not a valid representation for an object of typepublic <T> T fromJson(JsonReader reader, java.lang.reflect.Type typeOfT) throws JsonIOException, JsonSyntaxException
reader
and convert 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 type unsafe and should be used carefullyJsonIOException
- if there was a problem writing to the ReaderJsonSyntaxException
- if json is not a valid representation for an object of typepublic <T> T fromJson(JsonElement json, java.lang.Class<T> classOfT) throws JsonSyntaxException
fromJson(JsonElement, Type)
.T
- the type of the desired objectjson
- the root of the parse tree of JsonElement
s from which the object is to
be deserializedclassOfT
- The class of Tnull
if json
is null
.JsonSyntaxException
- if json is not a valid representation for an object of type typeOfTpublic <T> T fromJson(JsonElement json, java.lang.reflect.Type typeOfT) throws JsonSyntaxException
fromJson(JsonElement, Class)
instead.T
- the type of the desired objectjson
- the root of the parse tree of JsonElement
s from which the object is to
be deserializedtypeOfT
- 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 typeOfT = new TypeToken<Collection<Foo>>(){}.getType();
null
if json
is null
.JsonSyntaxException
- if json is not a valid representation for an object of type typeOfTpublic java.lang.String toString()
toString
in class java.lang.Object
Copyright © 2010 - 2020 Adobe. All Rights Reserved