How do I convert Map into JSON?

This example show you how to convert a java.util.Map into JSON string and back to Map again.

Here is the result of the program:

How do I convert collections into JSON?

This example show you how to convert Java collections object into JSON string. For Student class use in this example you can find it the previous example on How do I convert object into JSON?.

Here is the result of our program:

How do I convert array into JSON?

In the example below you can see how to convert an array into JSON string. We serialize the array to JSON using the Gson.toJson() method. To deserialize a string of JSON into array we use the Gson.fromJson() method.

Here is our code result:

How does Gson handles object’s fields?

In this example you’ll see how the Gson library handles the object fields. For object fields to be serialized into JSON string it doesn’t need to use any annotations, it can even read private fields. If you have a null value field it will not be serialized into JSON string. To exclude a field from serialization you can mark the field with the transient keyword.

In the snippet below we create a People object. This object has a null value field named age, this will not included in the serialization because we didn’t assign any value to it. The secret field is also not serialized because we mark it with transient keyword.

If your run the code above you’ll see the following line printed:

Here is the People class.