Introduction to the GSON and how to use it

Updated 10 June 2017

Save

In this blog, we are going to tell about the google’s GSON library. How to parse JSON to Java objects and vice-versa.

What is GSON?

Gson is a Java library that can be used to parse the Java Objects into their JSON and vice-versa. It can also be used to convert a JSON string to an equivalent Java object.

Google developed GSON for internal use but open sourced it later.

For this purpose, Gson provides several built-in serializers and deserializers.

Serializers:  A serializer allows to convert a Json string to corresponding Java Model or objects.

Deserializer: A deserializer allows to convert from Java Model to a JSON representation. You can also configure Gson to use custom representations of your objects.

Gson allows serializing an Collections of objects of the same type.

For use Gson in a Gradle build, add

or a later version as dependency to your build.gradl e build file.

How to use the GSON with JAVA Objects or JAVA Models

There are two methods to create an Gson instance:

new Gson()

We can simply create the GSON by below method:

GsonBuilder.build()

Here is an example of creating a GsonBuilder and calling:create()

Using a GsonBuilder allows you to set configuration options on the GsonBuilder before creating the Gsonobject.

Parsing JSON Into Java Objects

GSON can parse JSON into Java objects using the fromJson() method of the Gson object. Below is a GSON example of parsing JSON into a Java object or Model:

 

Below is how the Cloth model class looks:

 

Getting JSON From Java Objects or Models

GSON can also generate JSON from Java objects. You do so via the Gson object. To generate JSON you call the toJson() method of the Gson object. Here is an example of generating JSON from a Java object with GSON:

How to Print JSON Pretty

Here is an example of the compact JSON output from a default Gson instance:

However, this compact JSON can be hard to read. Therefore GSON offers a pretty printing option where the JSON is printed so it is more readable in a text editor.

Here is an example of how to create a Gson instance with pretty print enabled:

Here is an example of how the same JSON would look pretty-printed:

Thank you for reading it, maybe it will help you to understand the Basis GSON.

Happy Coding, Stay Super and Stay Cool.

 

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home