Ask Sawal

Discussion Forum
Notification Icon1
Write Answer Icon
Add Question Icon

when to use gson?

4 Answer(s) Available
Answer # 1 #

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.

Gson can work with arbitrary Java objects including pre-existing objects that you do not have source code of.

Here are some metrics that we obtained on a desktop (dual opteron, 8GB RAM, 64-bit Ubuntu) running lots of other things along-with the tests. You can rerun these tests by using the class PerformanceTest.

Note: Delete the disabled_ prefix to run these tests. We use this prefix to prevent running these tests every time we run JUnit tests.

Gson was originally created for use inside Google where it is currently used in a number of projects. It is now used by a number of public projects and companies.

The primary class to use is Gson which you can just create by calling new Gson(). There is also a class GsonBuilder available that can be used to create a Gson instance with various settings like version control and so on.

The Gson instance does not maintain any state while invoking JSON operations. So, you are free to reuse the same object for multiple JSON serialization and deserialization operations.

To use Gson with Maven2/3, you can use the Gson version available in Maven Central by adding the following dependency:

That is it, now your Maven project is Gson enabled.

Note that you can not serialize objects with circular references since that will result in infinite recursion.

Gson can serialize static nested classes quite easily.

Gson can also deserialize static nested classes. However, Gson can not automatically deserialize the pure inner classes since their no-args constructor also need a reference to the containing Object which is not available at the time of deserialization. You can address this problem by either making the inner class static or by providing a custom InstanceCreator for it. Here is an example:

NOTE: The above class B can not (by default) be serialized with Gson.

Gson can not deserialize {"b":"abc"} into an instance of B since the class B is an inner class. If it was defined as static class B then Gson would have been able to deserialize the string. Another solution is to write a custom instance creator for B.

The above is possible, but not recommended.

We also support multi-dimensional arrays, with arbitrarily complex element types.

Fairly hideous: note how we define the type of collection. Unfortunately, there is no way to get around this in Java.

Gson can serialize collection of arbitrary objects but can not deserialize from it, because there is no way for the user to indicate the type of the resulting object. Instead, while deserializing, the Collection must be of a specific, generic type. This makes sense, and is rarely a problem when following good Java coding practices.

Gson by default serializes any java.util.Map implementation as a JSON object. Because JSON objects only support strings as member names, Gson converts the Map keys to strings by calling toString() on them, and using "null" for null keys:

For deserialization Gson uses the read method of the TypeAdapter registered for the Map key type. Similar to the Collection example shown above, for deserialization a TypeToken has to be used to tell Gson what types the Map keys and values have:

Gson also supports using complex types as Map keys. This feature can be enabled with GsonBuilder.enableComplexMapKeySerialization(). If enabled, Gson uses the write method of the TypeAdapter registered for the Map key type to serialize the keys, instead of using toString(). When any of the keys is serialized by the adapter as JSON array or JSON object, Gson will serialize the complete Map as JSON array, consisting of key-value pairs (encoded as JSON array). Otherwise, if none of the keys is serialized as a JSON array or JSON object, Gson will use a JSON object to encode the Map:

Important: Because Gson by default uses toString() to serialize Map keys, this can lead to malformed encoded keys or can cause mismatch between serialization and deserialization of the keys, for example when toString() is not properly implemented. A workaround for this can be to use enableComplexMapKeySerialization() to make sure the TypeAdapter registered for the Map key type is used for deserialization and serialization. As shown in the example above, when none of the keys are serialized by the adapter as JSON array or JSON object, the Map is serialized as a regular JSON object, as desired.

Note that when deserializing enums as Map keys, if Gson is unable to find an enum constant with a matching name() value respectively @SerializedName annotation, it falls back to looking up the enum constant by its toString() value. This is to work around the issue described above, but only applies to enum constants.

When you call toJson(obj), Gson calls obj.getClass() to get information on the fields to serialize. Similarly, you can typically pass MyClass.class object in the fromJson(json, MyClass.class) method. This works fine if the object is a non-generic type. However, if the object is of a generic type, then the Generic type information is lost because of Java Type Erasure. Here is an example illustrating the point:

The above code fails to interpret value as type Bar because Gson invokes foo.getClass() to get its class information, but this method returns a raw class, Foo.class. This means that Gson has no way of knowing that this is an object of type Foo, and not just plain Foo.

You can solve this problem by specifying the correct parameterized type for your generic type. You can do this by using the TypeToken class.

The idiom used to get fooType actually defines an anonymous local inner class containing a method getType() that returns the fully parameterized type.

Sometimes you are dealing with JSON array that contains mixed types. For example:

The equivalent Collection containing this is:

where the Event class is defined as:

You can serialize the collection with Gson without doing anything specific: toJson(collection) would write out the desired output.

However, deserialization with fromJson(json, Collection.class) will not work since Gson has no way of knowing how to map the input to the types. Gson requires that you provide a genericised version of collection type in fromJson(). So, you have three options:

This approach is practical only if the array appears as a top-level element or if you can change the field type holding the collection to be of type Collection.

Gson has built-in serializers and deserializers for commonly used classes whose default representation may be inappropriate, for instance

For many more, see the internal class TypeAdapters.

You can also find source code for some commonly used classes such as JodaTime at this page.

Sometimes default representation is not what you want. This is often the case when dealing with library classes (DateTime, etc). Gson allows you to register your own custom serializers and deserializers. This is done by defining two parts:

registerTypeAdapter call checks if the type adapter implements more than one of these interfaces and register it for all of them.

Here is an example of how to write a custom serializer for JodaTime DateTime class.

Gson calls serialize() when it runs into a DateTime object during serialization.

Here is an example of how to write a custom deserializer for JodaTime DateTime class.

Gson calls deserialize when it needs to deserialize a JSON string fragment into a DateTime object

Finer points with Serializers and Deserializers

Often you want to register a single handler for all generic types corresponding to a raw type

Gson supports registering a single handler for this. You can also register a specific handler for a specific generic type (say Id needed special handling). The Type parameter for the toJson() and fromJson() contains the generic type information to help you write a single handler for all generic types corresponding to the same raw type.

While deserializing an Object, Gson needs to create a default instance of the class. Well-behaved classes that are meant for serialization and deserialization should have a no-argument constructor.

Typically, Instance Creators are needed when you are dealing with a library class that does NOT define a no-argument constructor

Instance Creator Example

Type could be of a corresponding generic type

Sometimes the type that you are trying to instantiate is a parameterized type. Generally, this is not a problem since the actual instance is of raw type. Here is an example:

However, sometimes you do need to create instance based on the actual parameterized type. In this case, you can use the type parameter being passed to the createInstance method. Here is an example:

In the above example, an instance of the Id class can not be created without actually passing in the actual type for the parameterized type. We solve this problem by using the passed method parameter, type. The type object in this case is the Java parameterized type representation of Id where the actual instance should be bound to Id. Since Id class has just one parameterized type parameter, T, we use the zeroth element of the type array returned by getActualTypeArgument() which will hold Foo.class in this case.

The default JSON output that is provided by Gson is a compact JSON format. This means that there will not be any whitespace in the output JSON structure. Therefore, there will be no whitespace between field names and its value, object fields, and objects within arrays in the JSON output. As well, "null" fields will be ignored in the output (NOTE: null values will still be included in collections/arrays of objects). See the Null Object Support section for information on configure Gson to output all null values.

If you would like to use the Pretty Print feature, you must configure your Gson instance using the GsonBuilder. The JsonFormatter is not exposed through our public API, so the client is unable to configure the default print settings/margins for the JSON output. For now, we only provide a default JsonPrintFormatter that has default line length of 80 character, 2 character indentation, and 4 character right margin.

The following is an example shows how to configure a Gson instance to use the default JsonPrintFormatter instead of the JsonCompactFormatter:

The default behaviour that is implemented in Gson is that null object fields are ignored. This allows for a more compact output format; however, the client must define a default value for these fields as the JSON format is converted back into its Java form.

Here's how you would configure a Gson instance to output null:

NOTE: when serializing nulls with Gson, it will add a JsonNull element to the JsonElement structure. Therefore, this object can be used in custom serialization/deserialization.

Here's an example:

The output is:

Multiple versions of the same object can be maintained by using @Since annotation. This annotation can be used on Classes, Fields and, in a future release, Methods. In order to leverage this feature, you must configure your Gson instance to ignore any field/object that is greater than some version number. If no version is set on the Gson instance then it will serialize and deserialize all fields and classes regardless of the version.

The output is:

Gson supports numerous mechanisms for excluding top-level classes, fields and field types. Below are pluggable mechanisms that allow field and class exclusion. If none of the below mechanisms satisfy your needs then you can always use custom serializers and deserializers.

By default, if you mark a field as transient, it will be excluded. As well, if a field is marked as static then by default it will be excluded. If you want to include some transient fields then you can do the following:

NOTE: you can give any number of the Modifier constants to the excludeFieldsWithModifiers method. For example:

This feature provides a way where you can mark certain fields of your objects to be excluded for consideration for serialization and deserialization to JSON. To use this annotation, you must create Gson by using new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(). The Gson instance created will exclude all fields in a class that are not marked with @Expose annotation.

If the above mechanisms for excluding fields and class type do not work for you then you can always write your own exclusion strategy and plug it into Gson. See the ExclusionStrategy JavaDoc for more information.

The following example shows how to exclude fields marked with a specific @Foo annotation and excludes top-level types (or declared field type) of class String.

The output is:

Gson supports some pre-defined field naming policies to convert the standard Java field names (i.e., camel cased names starting with lower case --- sampleFieldNameInJava) to a JSON field name (i.e., sample_field_name_in_java or SampleFieldNameInJava). See the FieldNamingPolicy class for information on the pre-defined naming policies.

It also has an annotation based strategy to allows clients to define custom names on a per field basis. Note, that the annotation based strategy has field name validation which will raise "Runtime" exceptions if an invalid field name is provided as the annotation value.

The following is an example of how to use both Gson naming policy features:

The output is:

If you have a need for custom naming policy (see this discussion), you can use the @SerializedName annotation.

Sometimes you need to share state across custom serializers/deserializers (see this discussion). You can use the following three strategies to accomplish this:

1 and 2 are not thread-safe options, but 3 is.

In addition Gson's object model and data binding, you can use Gson to read from and write to a stream. You can also combine streaming and object model access to get the best of both approaches.

See the Gson design document for a discussion of issues we faced while designing Gson. It also include a comparison of Gson with other Java libraries that can be used for JSON conversion.

[4]
Edit
Query
Report
Stroh noemtgvo Sandeep
WAD LUBRICATOR
Answer # 2 #

Google Gson is a simple Java-based library to serialize Java objects to JSON and vice versa. It is an open-source library developed by Google.

The following points highlight why you should be using this library −

Here is a list of some of the most prominent features of Gson −

Gson provides three alternative ways to process JSON −

It reads and writes JSON content as discrete events. JsonReader and JsonWriter read/write the data as token, referred as JsonToken.

It is the most powerful approach among the three approaches to process JSON. It has the lowest overhead and it is quite fast in read/write operations. It is analogous to Stax parser for XML.

It prepares an in-memory tree representation of the JSON document. It builds a tree of JsonObject nodes. It is a flexible approach and is analogous to DOM parser for XML.

It converts JSON to and from POJO (Plain Old Java Object) using property accessor. Gson reads/writes JSON using data type adapters. It is analogous to JAXB parser for XML.

If you still want to set up a local environment for Java programming language, then this section will guide you on how to download and set up Java on your machine. Please follow the steps given below, to set up the environment.

Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Follow the instructions to download Java and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set the environment variables to point to their correct installation directories.

Assuming you have installed Java in c:\Program Files\java\jdk directory −

Assuming you have installed Java in c:\Program Files\java\jdk directory −

The environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this.

For example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH=/path/to/java:$PATH'

To write your Java programs, you will need a text editor. There are quite a few sophisticated IDEs available in the market. But for now, you can consider one of the following −

Download the latest version of Gson jar file from gson-2.3.1.jar. At the time of writing this tutorial, we downloaded gson-2.3.1.jar and copied it into C:\>gson folder.

Set the GSON_HOME environment variable to point to the base directory location where Gson jar is stored on your machine.

Set the CLASSPATH environment variable to point to the Gson jar location.

Before going into the details of the Google Gson library, let's see an application in action. In this example, we've created a Student class. We'll create a JSON string with student details and deserialize it to student object and then serialize it to an JSON String.

Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.

File − GsonTester.java

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

Following are the important steps to be considered here.

Create a Gson object. It is a reusable object.

Use fromJson() method to get the Object from the JSON. Pass Json string / source of Json string and object type as parameter.

Use toJson() method to get the JSON string representation of an object.

Gson is the main actor class of Google Gson library. It provides functionalities to convert Java objects to matching JSON constructs and vice versa. Gson is first constructed using GsonBuilder and then, toJson(Object) or fromJson(String, Class) methods are used to read/write JSON constructs.

Following is the declaration for com.google.gson.Gson class −

This class inherits methods from the following class −

Create the following Java program using any editor of your choice, and save it at, say, C:/> GSON_WORKSPACE

File − GsonTester.java

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output

Let's serialize a Java object to a Json file and then read that Json file to get the object back. In this example, we've created a Student class. We'll create a student.json file which will have a json representation of Student object.

Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the Output

Data Binding API is used to convert JSON to and from POJO (Plain Old Java Object) using property accessor or using annotations. It is of two types.

Gson reads/writes JSON for both types of data bindings. Data Binding is analogous to JAXB parser for XML.

Primitives data binding refers to mapping of JSON to JAVA Core data types and inbuilt collections. Gson provides various inbuilt adapters which can be used to serialize/deserialize primitive data types.

Let's see primitive data binding in action. Here we'll map JAVA basic types directly to JSON and vice versa.

Create a Java class file named GsonTester in C:\>Gson_WORKSPACE.

File − GsonTester.java

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

Object data binding refers to mapping of JSON to any JAVA Object.

Let's see object data binding in action. Here we'll map JAVA Object directly to JSON and vice versa.

Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

Tree Model prepares an in-memory tree representation of the JSON document. It builds a tree of JsonObject nodes. It is a flexible approach and is analogous to DOM parser for XML.

JsonParser provides a pointer to the root node of the tree after reading the JSON. Root Node can be used to traverse the complete tree. Consider the following code snippet to get the root node of a provided JSON String.

Get each node using relative path to the root node while traversing the tree and process the data. The following code snippet shows how you can traverse a tree.

Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.

File − GsonTester.java

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

Streaming API is used to read JSON token by token. It reads and writes JSON content as discrete events. JsonReader and JsonWriter read/write the data as token, referred as JsonToken.

It is the most powerful approach among the three approaches to process JSON. It has the lowest overhead and it is quite fast in read/write operations. It is analogous to Stax parser for XML.

In this chapter, we will showcase the usage of GSON streaming APIs to read JSON data. Streaming API works with the concept of token and every details of Json is to be handled carefully.

Let's see JsonReader in action. Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

In this chapter, we will discuss the serialization/deserialization of arrays, collections, and generics.

Let's see Array serialization/de-serialization in action. Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.

File − GsonTester.java

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

Let's see Collection serialization/de-serialization in action. Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.

File − GsonTester.java

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

Gson uses Java reflection API to get the type of the object to which a Json text is to be mapped. But with generics, this information is lost during serialization. To counter this problem, Gson provides a class com.google.gson.reflect.TypeToken to store the type of the generic object.

Let's see Generics serialization/de-serialization in action. Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.

File − GsonTester.java

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

In this chapter, we will explain serialization/deserialization of classes having inner classes.

Let's see an example of serialization/de-serialization of class with an inner class in action. Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.

File − GsonTester.java

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

Let's see an example of serialization/de-serialization of class with a static inner class in action. Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.

File − GsonTester.java

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

Gson performs the serialization/deserialization of objects using its inbuilt adapters. It also supports custom adapters. Let’s discuss how you can create a custom adapter and how you can use it.

Create a custom adapter by extending the TypeAdapter class and passing it the type of object targeted. Override the read and write methods to do perform custom deserialization and serialization respectively.

Register the custom adapter using GsonBuilder and create a Gson instance using GsonBuilder.

Gson will now use the custom adapter to convert Json text to object and vice versa.

Let's see an example of custom type adapter in action. Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.

File − GsonTester.java

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

Gson by default generates optimized Json content ignoring the NULL values. But GsonBuilder provides flags to show NULL values in the Json output using the GsonBuilder.serializeNulls() method.

Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

Gson provides @Since annotation to control the Json serialization/deserialization of a class based on its various versions. Consider the following class with versioning support. In this class, we've initially defined two variables rollNo and name and later on, we added verified as a new variable. Using @Since, we've defined rollNo and name as of version 1.0 and verified to be of version 1.1.

GsonBuilder provides the setVersion() method to serialize such versioned class.

Let's see an example of versioning support in action. Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output.

By default, GSON excludes transient and static fields from the serialization/deserialization process. Let’s take a look at the following example.

Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.

File − GsonTester.java

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output

GsonBuilder provides control over excluding fields with particular modifier using excludeFieldsWithModifiers() method from serialization/deserialization process. See the following example.

Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.

File − GsonTester.java

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output

Gson provides @Expose annotation to control the Json serialization/deserialization of a class based on its scope. Consider the following class with a variable having @Expose support. In this class, name and rollno variables are to be exposed for serialization. Then we've used the GsonBuilder.excludeFieldsWithoutExposeAnnotation() method to indicate that only exposed variables are to be serialized/deserialized. See the following example.

Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.

File − GsonTester.java

Compile the classes using javac compiler as follows −

Now run the GsonTester to see the result −

Verify the output

[4]
Edit
Query
Report
Geetha Uday
CHEMICAL OPERATOR II
Answer # 3 #

Gson is one of the most popular Java JSON libraries. In this post I’ll pick a fairly complex JSON document and three queries which I want to make using Gson. I’ll compare two different approaches:

All the code used in this post is in this repository. It’ll work with Java 8 onwards.

The most popular Java libraries for working with JSON, as measured by usage in maven central and GitHub stars, are Jackson and Gson. In this post I will be using Gson. I also wrote an equivalent post with Jackson code examples.

You can see the Gson dependency for the examples here.

To find some example data I read Tilde’s recent post 7 cool APIs you didn’t know you needed, and picked out the Near Earth Object Web Service API from the NASA APIs. This API is maintained by the brilliantly-named SpaceRocks team.

The NeoWS Feed API request returns a list of all asteroids whose closest approach to Earth is within the next 7 days. I’ll be showing how answer the following questions in Java:

Gson allows you to read JSON into a tree model: Java objects that represent JSON objects, arrays and values. These objects are called things like JsonElement or JsonObject and are provided by Gson.

Pros:

Cons:

[3]
Edit
Query
Report
avxvrnmf Shingare
FUR CLEANER HAND
Answer # 4 #

Gson is a Java library that can be used to convert Java objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including objects for which you do not have the source.

[0]
Edit
Query
Report
Costa-Gavras Buttons
Obstetrical Nursing