Java Google Json (Gson) Introduction

Overview of The Gson API

google json – gson is an open source java api for parsing and building json. It has extensive support for java generics. It also provides support for converting third party classes to json. It can be used to serialize and deserialize complex objects with deep hierarchies that may contain generic classes. In these tutorials we demonstrate, with examples, the following functionalities of gson.

Gson 2.3: Look at this tutorial to see the latest additions in Gson 2.3 (TypeAdapter Annotation, JsonPath support and new methods in JsonArray)

  1. Java to JSON and Back – Data Binding – In this example we look at how to bind a Json to a java object. Gson is quite powerful when it comes to binding a json to Java since it has a lot of built in serializers and deserializers. A serializer has code that helps in converting a Json string to corresponding java type. For example if you have an array in JSON (elements enclosed in ‘[‘ and ‘]’) and you want to convert that to a Java array then Gson would internally use an ArrayTypeAdapter to convert the Json Array to Java Array and back. If you are looking at Gson primarily to parse JSON then we would suggest that you start with a simple Java class, convert that to JSON and make sure it looks like the JSON that you want to parse. You can then gradually start adding complexities to the java class and at each step convert it to a JSON and ensure that the JSON is similar to the one that you are trying to parse. It is good to
    think of parsing a JSON as creating a java class that can give you the JSON that you want to parse. Also note that you have certain flexibility while creating the java object. You could represent a Json Array as a Java array or a Java List. The choice may be driven more by how you want to use the class. If you map a Json property to a java array Gson would use an Array adapter but if you map it to a List it would use the collection adapter and you, the user, does not have to worry about that. Gson also handles null gracefully
  2. Java to JSON and Back – Streaming – At certain times you want more control on the way the parsing is done. Also there may be times when Gson automated conversion does not give you the result that you are looking for. For example, if you have a List that contains multiple kinds of Object then Gson may not be able to deserialize or parse the Json for you. In such cases Gson provides a streaming API. You can use the Streaming API and handle a token at a time. The token may be start and end of Json Object, start and end of json array, the key of a property and the String or Number value of a property.
  3. Java to JSON and Back – Tree representation – The first two examples look at how to convert JSON to Java using data binding and a Streaming API. This tutorial explains a third way to parse JSON, i.e. by building a Java tree representation of the JSON. The nodes of the tree may either be a JsonObject or a JsonArray. The JsonObject has methods to retrive the key-value pairs of the JSON. The JsonArray provides way to iterate over the elements of the array which are themselves either a JsonObject or a JsonArray.
  4. Serializing a list Serializing Collections require special treatment since the Collections are of generic type and the type information is lost while converting to JSON due to java type erasure. Gson handles this by embedding the type in the serialized json. This tutorial explains how to do that.
  5. Serializing and deserializing Java Generic Classes – In the first example we saw how to bind a java Object to JSON. However, the example there did not show how Gson can handle classes with generic type. In this example we see how a class with a generic type can be handled. the idea is to embed the type information in the json itself so that Gson can recreate the Java Object along with the correct generic type while deserializing the JSON.
  6. Serializing Inner Classes– GSON provides ways to serialize inner classes. The example in this tutorial explains the following:
    1. Serializing class containing static nested class
    2. Serializing class containing non static nested class (Inner class)
    3. De-serializing json to a class containing static and non static inner class
    4. Serializing static nested class (without the enclosing type)
    5. Serializing non static nested class (without the enclosing type)
    6. De-serializing json to a static nested class (without the enclosing type)
    7. De-serializing json to a non static nested class (without the enclosing type)
  7. Using Custom type adapters – GSON provides pre definied type adapters that are called when serializing or deserializing certain java types. For example an ArrayTypeAdapter is called when Gson encounters a Java Array that needs to be converted to JSON. In most cases the TypeAdapters provided by GSON would suffice, however in certain cases you may want to write your own adapters. There are two reasons for doing that i) You want to change the default behavious ii) GSON does not provide adapter for your class.
  8. Using Custom Serialization and Deserialization classes – In the previous example we saw how JSON provides a way to write a custom adapter. In this example we see how to write a custom serializer or deserializer.
  9. Excluding certain fields from Java classes Your java class may be used by various other layers of the application. In some cases your java class may have properties that you want GSON to ignore from serialization. This example provides three ways to exclude properties from serialization and de serialization.
    1. Custom annotations
    2. Using custom Exclusion Strategies
    3. Using @Expose annotation

6 thoughts on “Java Google Json (Gson) Introduction”

  1. “A serializer has code that helps in converting a Json string to corresponding java type”
    That is incorrect. A serializer has code that helps in converting from a Java type to another representation, in this case, that would be a Json string.

    Reply
    • technically, both statements are referring to marshalling and unmarshalling – the direction to/from depends on the perspective.

      Reply
  2. Some other links are broken too (e.g. “Serializing and deserializing Java Generic Classes”). It would be awesome if you could check all the links as this is the main documentation of GSON…
    Cheers!

    Reply
  3. Hi Team,

    Due to vulnerability in the Gson version below 2.8.9, we updated the Gson version and Junit to 4.13.2 but post version update of Gson to 2.8.9 we started facing test case failure.
    Does anyone find the fix for the same. Kindly respond if it is fixed.

    java.lang.NoSuchFieldError: FACTORY
    at com.google.gson.Gson.(Gson.java:200)
    at com.google.gson.GsonBuilder.create(GsonBuilder.java:572)

    Reply

Leave a Comment