Gson Tutorial

All modern applications generally fetch data from remote services (e.g. REST or SOAP). The data is mostly either XML or JSON format. Gson helps applications in Java-JSON serialization and deserialization automatically (as well as manually, if needed, using simple toJson() and fromJson() methods).

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

The best benefit of Gson is that it does not make mandatory to add annotations into java classes, until we are doing something very specific for certain member fields.

Note that 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.

In this Gson tutorial, we will learn to use it effectively in our applications.

1. Gson Fundamentals

In this first part, we will get to know Google Gson library and its basic mapping functionality.

  • Installation

    Learn to include gson dependency in the java applications using build tools like maven, gradle or simple jar file.

  • Simple Serialization and deserialization

    Learn to use GSON to serialize simple Java Object into the JSON representation and to deserialize the JSON string to an equivalent Java object.

  • Compact Vs. Pretty Printing for JSON Output Format

    The default JSON output that is provided by Gson is a compact JSON format. Use the Pretty Print feature to format the JSON for reading purpose.

  • Mapping of Arrays and Lists of Objects

    Learn to use Google GSON library to deserialize or parse JSON, containing json array, to java array or java list objects.

  • Mapping of Sets

    Learn to use Google GSON library to deserialize or parse JSON to Set (e.g. HashSet) in java.

  • Mapping of Maps

    Learn to serialize HashMap using Google Gson library. Also learn to deserialize JSON string to HashMap containing custom Objects using Gson such that field values are copied into appropriate generic types.

2. Advance Usages

Basic examples in first part are good enough for default usecases. We may need to customize the behavior of Gson to support specific requirements. Learn how to do this.

Drop me your questions related to this gson tutorial.

Happy Learning !!

References:

Google Gson on Github

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.