How to Convert Java Object to/from JSON using GSON

Gson is Java JSON library that is used to convert Java object to/from JSON

GSON is developed by google.

GSON Maven dependency is as below

You can also download Gson Jar from here

Gson jar contains API to work with JSON

GOal of GSON is provide simple methods to convert and receive JSON, Provides extensive support for Generics, support complex objects

GSON provides simple functions to convert in to JSON it has toJSON() and from JSON to Java Object it has fromJSON()

Creating JSON Object

1. Gson gson=new Gson();
2. GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson1 = gsonBuilder.create();

Here Gson() is no argument constructor that will create Gson object.

Using GsonBuilder by calling create() we get Gson object

Converting Java to JSON value

Result:

Some times JSON is difficult to read to make JSON readable .setPrettyPrinting() can be used as below

GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson1= gsonBuilder.setPrettyPrinting().create();

Replace line 40 of program with second line of above code.

Then output is as below.

Serializing a custom object

Here a student class is defined it contains Address class. Create object of student and serializing it as below

Student.java

Address.java

Result

Reading Json Data from file

Parsing JSON to Java is prerformed as here.

We have saved JSON of a student (same as above structure few parameter changed) in student.json file then we are reading its content from student.json.

student = gson.fromJson(new FileReader(“d://student.json”), Student.class);

To read file from student.json File reader is used. after reading file it is converted to Student type.

Result

Reading JSON data from URL

  1. Open Connection with url
  2. Read Data using InputStreamReader
  3. Pass InputStreamReader to fromJson()

Working code is as below

@Expose annotation to serialize and de serialize fields

Annotation Export is used to serialize and deserialize fields it is defined in import com.google.gson.annotations.Expose

@Expose(serialize = true, deserialize = true) is used serialize true represents it has to be serialize same for deserialize. false value is used to not include the field in process of serialize or deserialize.

Above code Student.java and Address.java is modified as below

in main method to create object we have to use GsonBuilder as below call a method excludeFieldWithoutExposeAnnotation()

ExclusionStrategy Interface

This interface is also used to exclude any field in serializing and deserialization.

To implement ExcludeStrategy a class has to implement this.

Below is an example to remove fname field from serialization

To create Gson object use GsonBuilder as below