This is follow-up article to previous Getting Started with Google GSON where it shows the introductory material on using the Google Gson.
This article shows some extra goodies of GSON library. As there are lot of things to write about these extra goodies, so i splitted long article into 2 article series, So, this part one of it and in coming next article, i will be posting rest of remaining stuff.
The beauty in using GSON library is that, it does not require any annotations or configurations for simple conversions. Although it makes use of default configurations to keep things simple. GSON has flexibility in creating the Json from Java object and vice-versa. Our truly Gson class contains lot of defaults for json conversion but we can override the defaults with use of class GsonBuilder. So, lets get started.
Pretty Formatted JSON output
When you print the json output string created using Gson then you will see output in one line, something like following
This is default formatting mode called Compact mode. It gets harder to read when your json has with lots fields and components. For proper formatting, the library has the nice pretty formatting mode which prints the each field in one line
To use this, you need to create Gson instance with GsonBuilder#setPrettyPrinting() as shown in following listing
Following is the our class, whose object to converted to its json representation,
Note line no. 7 for use,
and output for above is
Including null fields in JSON output
By default, in conversion null value fields are ignored while converting to Json format. This is just to make output clear and compact.
But we can override this behaviour by creating the Gson instance with GsonBuilder #serializeNulls(). Following listing shows
Note line no .11 for use,
Note the output for the above, classz is included
Including the custom name
By default, json output field names are the same as the class field names. Gson provides the way to change this with use of an annotation.
For this we need to use @serilizedName annotation provided for the field which we need to change the name in output json.
So, our Developer class we change the name to firstName
and if we run following then
then in output we will have the “firstName” instead of “name”
Writing the JSON to/from stream
Gson library has one overload to each method, toJson() and fromJson(), for writing and reading from streams respectively. In simple words, you can write json output to file, character, or buffer and you can read from any Reader stream.
Following listing shows, writing and reading JSON to/from File stream