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.
This is how a Java object will lookin JSON format
Override toString() to print object as JSON
Let’s add (override) the method toString to our Book class to print any Book Java object as JSON.
Now we’re going to print our Java object as JSON
Readable console output in JSON format
Java objects in JSON format (JSON objects) now look much better. Feel the difference.
Print any Java object as JSON
In general you can print any Java object as JSON.
Note: It prints all object’s fields even if they are also objects