Hands on GSON
This chapter introduces the GSON library that simplifies the use of JSON in Java.
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.
There are a few open-source projects that can convert Java objects to JSON. However, most of them require that you place Java annotations in your classes; something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. Gson considers both of these as very important design goals.
Gson Goals:
Provide simple
toJson()
andfromJson()
methods to convert Java objects to JSON and vice-versaAllow pre-existing unmodifiable objects to be converted to and from JSON
Extensive support of Java Generics
Allow custom representations for objects
Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)
Adding Gson as a Dependency
Start by creating a simple Java Maven Application (no JavaFX application). Call it for example JavaGsonExample
.
You starter code should be looking familiar from the first part of this course:
Adding the Library as a dependency
Add the following dependency to your pom.xml
file inside your project.
End result:
Step 2 - Simple Object Serialization
Gson can easily serialize and deserialize objects to and from json.
Serialization is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer) or transmitted (for example, across a network connection link) and reconstructed later (possibly in a different computer environment). When the resulting series of bits is reread according to the serialization format, it can be used to create a semantically identical clone of the original object. This process of serializing an object is also called marshalling an object. The opposite operation, extracting a data structure from a series of bytes, is deserialization (which is also called unmarshalling).
Some things to know about Gson serialization:
You can not serialize objects with circular references since that will result in infinite recursion.
It is perfectly fine (and recommended) to use private fields.
There is no need to use any annotations to indicate an attribute is to be included for serialization and deserialization. All fields in the current class (and from all super classes) are included by default.
If an attribute is marked transient, (by default) it is ignored and not included in the JSON serialization or deserialization.
While serializing, a null attribute is omitted from the output.
While deserializing, a missing entry in JSON results in setting the corresponding attribute in the object to its default value: null for object types, zero for numeric types, and false for booleans.
If an attribute is synthetic, it is ignored and not included in JSON serialization or deserialization.
Fields corresponding to the outer classes in inner classes, anonymous classes, and local classes are ignored and not included in serialization or deserialization.
A Motorcycle class
Let us create a Motorcycle class with the following characteristics:
a brand:
String
- for example "Kawasaki"a model:
String
- for example "VN800"a year of manufacturing:
int
- for example 1997a price:
double
- for example 5000
We create a simple class with a constructor that takes the first three attributes as arguments. The price
is considered optional as we do not always know the price of the model.
Let us implement a small test application in main:
This should output:
Now we know our class works.
Serialization of a Motorcycle
Below is the part of the example that is of importance to us. BagOfPrimitives
is the name of the class of the object that is being serialized.
So all we need to do is create an object of the class Gson
and call the method toJson()
with an instance of the object we want to serialize.
For example:
The result of this is:
Deserialization of a Motorcycle
To deserialize a Motorcycle
object from a json we start by creating our own json. For this we will need to adhere to the resulting json format outputted by the previous example.
or one without a price:
When you copy paste these json strings in NetBeans, they will automatically be escaped.
Deserializing the json
Again we start with the example given on the GitHub UserGuide.
Again we need an object of the class Gson
. This time we need to call the method fromJson()
and pass two arguments. First the json String and secondly the name of the class. The second argument is given by following the class with .class
, for example Motorcycle.class
.
Let us try it out:
Resulting in:
Composition
But what if we included a reference to an object of another class? Take for example a class Engine
that contains the specific engine specs.
Of course we also need to adjust our Motorcycle
class a bit to take this Engine
class in account.
A new Main
Since we changed quite a bit we'll start over with a new main (you can also comment out the previous code so not to lose it).
The Motorcycle
constructors requires us to pass it an Engine
object, so we will need to create this before we create a new Motorcycle
. Once that is done we can just serialize and deserialize and we did before.
which results in:
Last updated