Enterprise Java

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");
  }
}

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);

and output for above is

********* Compact mode ***********
{"name":"ajduke","languagesKnown":["Java","Scala","Ruby"]}

 ******* Pretty formatting *********
{
  "name": "ajduke",
  "languagesKnown": [
    "Java",
    "Scala",
    "Ruby"
  ]
}

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");
  }
}

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);

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"
  ]
}

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");
  }
}

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);

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"
  ]
}

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 + "]";
  }
}

 

Reference: Using Google GSON : Extra Goodies : Part I from our JCG partner Abhijeet Sutar at the ajduke’s blog blog.

Abhijeet Sutar

Abhijeet (ajduke) is self-taught, self-organized software developer. His current go to language is Java and also he is exploring other languages such as Scala, Ruby.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button