GSON

Gson is an open-source Java library developed by Google that converts Java Objects into their JSON representation and vice versa.

Gson mainly build for Java, other jvm languages may not work properly. It

  • Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa

  • Allow pre-existing unmodifiable objects to be converted to and from JSON

  • Extensive support of Java Generics and Allow custom representations for objects

Dependency

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>${version}</version>
</dependency>

Some points to consider

  • We can use private fields, they will be serialized.

  • All fields in the current class (and from all super classes) are included by default.

  • If a field is marked transient, (by default) it is ignored and not included in the JSON serialization or deserialization.

  • This implementation handles nulls correctly.

    • While serializing, a null field is omitted from the output.

    • While deserializing, a missing entry in JSON results in setting the corresponding field in the object to its default value: null for object types, zero for numeric types, and false for booleans.

  • If a field is synthetic, it is ignored and not included in JSON serialization or deserialization.

  • Fields corresponding to the outer classes in inner classes are ignored and not included in serialization or deserialization.

  • Anonymous and local classes are excluded. They will be serialized as JSON null and when deserialized their JSON value is ignored and null is returned. Convert the classes to static nested classes to enable serialization and deserialization for them.

  • We cannot serialize objects with circular references, since that will result in infinite recursion.

Serialization and De-serialization

First we need to create Gson object by using the class Gson, then we can use methods like fromJson & toJson to do objects and json conversion.

TypeToken

TypeToken is a class in Gson that helps capture and preserve generic type information.

TypeToken is essential when working with generic types in Gson, and understanding its proper usage helps in handling complex JSON structures effectively.

TypeToken instances should be created carefully and reused when possible for better performance.

Examples

Primitives

Arrays Example

Collections Example

for the collections, we will be needing type tokens for conversion.

Maps Examples

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 a TypeToken has to be used to tell Gson what types the Map keys and values have:

Another Example

If map keys are complex and toString method is not implemented, then this can lead to malformed encoded keys or can cause mismatch between serialization and deserialization of the keys. 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.

Raw Collection Example

Objects Types-

If Object is in with collections -

Nested Structure with Multiple Types

Generic Types

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. To make it work properly we need to use TypeToken

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

Custom Serialization and Deserialization

Sometimes the 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:

  • JSON Serializers: Need to define custom serialization for an object

  • JSON Deserializers: Needed to define custom deserialization for a type

  • Instance Creators: Not needed if no-args constructor is available or a deserializer is registered

Custom Type Adapters

Instance Creator

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

Basic instance creator-

Instance Creator with parameterized type

Pretty Printing for JSON Output Format

Null Object Support

By default null object fields are ignored. To serialize them -

Excluding Fields From Serialization and Deserialization

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.

We can control this by using modifiers-

User Defined Exclusion Strategies

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:

JSON Field Naming Support

For defining custom name we can use @SerializedName annotation and can configure FieldNamingPolicy to serilization of fields

Best Practices -

  1. Use Pretty Printing for Debug

  2. Handle Null Values Appropriately

  3. Reuse Gson Instances

Inspired from - gson user guide

Last updated