Using Google GSON : Extra Goodies : Part I

Introduction

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

{"name":"ajduke","languagesKnown":["Java","Scala","JavaScript"]}

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,

class Developer {
private String name;
private String classz;
List<String> languagesKnown;
public Developer() {
name = "ajduke";
languagesKnown = new ArrayList<>();
languagesKnown.add("Java");
languagesKnown.add("Scala");
languagesKnown.add("Ruby");
}
}
view raw Developer.java hosted with ❤ by GitHub

Note line no. 7 for use,

Gson gson = new Gson();
String json = gson.toJson(new Developer());
System.out.println("********* Compact mode ***********");
System.out.println(json);
GsonBuilder gsonBuilder = new GsonBuilder();
Gson prettyGson = gsonBuilder.setPrettyPrinting().create();
json = prettyGson.toJson(new Developer());
System.out.println("\n ******* Pretty formatting *********");
System.out.println(json);
view raw Ex1.java hosted with ❤ by GitHub

and output for above is

********* Compact mode ***********
{"name":"ajduke","languagesKnown":["Java","Scala","Ruby"]}
******* Pretty formatting *********
{
"name": "ajduke",
"languagesKnown": [
"Java",
"Scala",
"Ruby"
]
}
view raw Ex1-Output hosted with ❤ by GitHub

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

class Developer {
private String name;
private String classz;
List<String> languagesKnown;
public Developer() {
name = "ajduke";
classz= "Developer";
languagesKnown = new ArrayList<>();
languagesKnown.add("Java");
languagesKnown.add("Scala");
languagesKnown.add("Ruby");
}
}
view raw Developer.java hosted with ❤ by GitHub

Note line no .11 for use,

Gson gson = new Gson();
System.out.println("Default behaviour ");
GsonBuilder gsonBuilder = new GsonBuilder();
Gson prettyGson = gsonBuilder.setPrettyPrinting().create();
String json = prettyGson.toJson(new Developer());
System.out.println(json);
System.out.println("Including the nulls ");
Gson includeNullsGson = gsonBuilder.serializeNulls().create();
String json2 = includeNullsGson.toJson(new Developer());
System.out.println(json2);
view raw Ex2.java hosted with ❤ by GitHub

Note the output for the above, classz is included

Default behaviour
{
"name": "ajduke",
"languagesKnown": [
"Java",
"Scala",
"Ruby"
]
}
Including the nulls
{
"name": "ajduke",
"classz": null,
"languagesKnown": [
"Java",
"Scala",
"Ruby"
]
}
view raw Ex2-Output hosted with ❤ by GitHub

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

class Developer {
@SerializedName("firstName")
private String name;
private String classz;
List<String> languagesKnown;
public Developer() {
name = "ajduke";
languagesKnown = new ArrayList<>();
languagesKnown.add("Java");
languagesKnown.add("Scala");
languagesKnown.add("Ruby");
}
}
view raw Developer4.java hosted with ❤ by GitHub

and if we run following then

Gson gson = new Gson();
String json = gson.toJson(new Developer());
System.out.println("********* Compact mode ***********");
System.out.println(json);
GsonBuilder gsonBuilder = new GsonBuilder();
Gson prettyGson = gsonBuilder.setPrettyPrinting().create();
json = prettyGson.toJson(new Developer());
System.out.println("\n ******* Pretty formatting *********");
System.out.println(json);
view raw Ex1.java hosted with ❤ by GitHub

then in output we will have the “firstName” instead of “name”

********* Compact mode ***********
{"firstName":"ajduke","languagesKnown":["Java","Scala","Ruby"]}
******* Pretty formatting *********
{
"firstName": "ajduke",
"languagesKnown": [
"Java",
"Scala",
"Ruby"
]
}
view raw Ex4-Output.txt hosted with ❤ by GitHub

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

package in.ajduke.ap013;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
public class GsonEx {
public static void main(String[] args) throws IOException {
Gson gson = new Gson();
System.out.println("Writing JSON to file ....");
// using try with resources
try (FileWriter writer = new FileWriter("d:/output.json")) {
gson.toJson(new Developer(), writer); // writing to file
}
System.out.println("Reading from file.. ");
FileReader fileReader = new FileReader("d:/output.json");
dev= gson.fromJson(fileReader, Developer.class);
System.out.println(dev);
}
}
class Developer {
private String name;
private String classz;
List<String> languagesKnown;
public Developer() {
name = "ajduke";
languagesKnown = new ArrayList<>();
languagesKnown.add("Java");
languagesKnown.add("Scala");
languagesKnown.add("Ruby");
}
@Override
public String toString() {
return "Developer [name=" + name + ", classz=" + classz
+ ", languagesKnown=" + languagesKnown + "]";
}
}
view raw Exe5.java hosted with ❤ by GitHub

One thought on “Using Google GSON : Extra Goodies : Part I

Add yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a free website or blog at WordPress.com.

Up ↑

%d bloggers like this: