Often we need to log or print objects and variables to the console/logs for debugging. Here is how to print an object as JSON in Java.
GSON. Maven Dependency
To print object as JSON we’re going to use Gson - a very powerful library for JSON serialization/deserialization (in the current context converting from object to JSON and from JSON to object).
Java object example
If we try to print this Java object
We get the output like this
That’s not very informative, is it?
We need all object’s fields printed.
Print object as JSON in Java
The JSON format and the Gson library let us print the Java object as JSON easily.
Override toString() to print object as JSON
Let’s add (actually override) the method toString into our Book class.
Now we’re going to print our object as JSON
Readable console output in JSON format
In JSON format the printed object looks much better. Feel the difference.
Print any object as JSON
In general you can print any Java object as JSON.
Note: It prints all object’s fields even if they are private or they are also objects
You may also find these posts interesting: