About 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.

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.
Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


+ two = 9



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books