GSON Instance Creation Using GsonBuilder

  1. Gson Instatiation using GsonBuilder
  2. Why We Need to use GsonBuilder When We Have Gson
  3. Key Methods of GsonBuilder With Explanation
  4. Syntax for Basic Way of Usage
  5. Simple Example of GsonBuilder() To alter Date Format as 'dd-MM-YYYY'
  6. GsonBuilder Example for excludeFieldsWithModifiers() Concept

>_Gson Instatiation using GsonBuilder

  • We can use this builder to construct a Gson instance when we need to set configuration options other than the default.

    For Gson with default configuration, it is simpler to use new GsonBuilder().create() . methods

    Gson gson = new GsonBuilder().create();

    While creating the gson instance as above we can use various configurations like versionSupport,null searlizatoin etc.. we will learn those later

>_Why We Need to use GsonBuilder When We Have Gson

    1. Gson is a class which convert everything like object=>json.
    2. If we want limit some of them from converting to json then Gson is use not useful.
    3. GsonBuilder comes with various settings to control the data convertion like
      1. Serializing Nulls
      2. Setting Custom DateFormat
      3. Version Control
      4. Setting Field Naming Policy
      5. Disabling HTML Escaping
      6. Excudling Some Fileds For JSON Convertion
      7. etc

    Once we have created a Gson instance we can start using it to parse and generate JSON.

>_Key Methods of GsonBuilder class

  • Method Name Description
    Gson create() Creates a Gson instance
    GsonBuilder setDateFormat(int style) Configures Gson to serialize Date objects according to the style value provided.
    GsonBuilder setDateFormat(String pattern) Configures Gson to serialize Date objects according to the pattern provided.
    GsonBuilder setVersion(double ignoreVersionsAfter) Configures Gson to enable versioning support.
    GsonBuilder excludeFieldsWithModifiers(int... modifiers) Configures Gson to excludes all class fields that have the specified modifiers.
    GsonBuilder excludeFieldsWithoutExposeAnnotation() Configures Gson to exclude all fields from consideration for serialization or deserialization that do not have the Expose annotation.
    Check this link to view GsonBuilder Class & its methods.

>_Basic Syntax and Usage

  • Syntax

     
    Gson gson = new	GsonBuilder() .registerTypeAdapter(Id.class, new IdTypeAdapter()) 
    .enableComplexMapKeySerialization().serializeNulls() .setDateFormat(DateFormat.LONG)
    .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
    .setPrettyPrinting() .setVersion(1.0) .create(); 

    the order of invocation of configuration methods does not matter.

>_Simple Example of GsonBuilder() To alter Date Format as 'dd-MM-YYYY'

  • /**
     * @author TutorialToUs.com
     */
    package com.tutorialtous.gson;
    
    import java.util.Date;
    
    import com.google.gson.Gson;
    import com.google.gson.GsonBuilder;
    
    public class GsonBuilderSimpleExample {
    	public static void main(String[] args) {
    		Date date = new Date();
    		Gson gson = null;
    		Gson gson2 = null;
    		gson = new GsonBuilder().create();
    		gson2 = new GsonBuilder().setDateFormat("dd-MM-YYYY").create();
    		System.out.println(gson.toJson(date));
    		System.out.println(gson2.toJson(date));
    
    	}
    }
    
    Output:-
    									
    "Jun 24, 2016 3:13:52 PM"
    "24-06-2016"
    

>_Example for excludeFieldsWithModifiers() Concept

  • /**
     * @author TutorialToUs.com
     */
    package com.tutorialtous.gson;
    
    import java.lang.reflect.Modifier;
    import com.google.gson.Gson;
    import com.google.gson.GsonBuilder;
    
    public class GsonBuilderExcludeModifierExample {
    	public static void main(String[] args) {
    		TableBeanEMP emp = new TableBeanEMP("JamesBond", "007", "01-01-1800",
    				"1800-007");
    
    		Gson gson = new GsonBuilder().excludeFieldsWithModifiers(
    				Modifier.STATIC).create();
    		Gson allgson = new GsonBuilder().excludeFieldsWithModifiers().create();
    		System.out.println(gson.toJson(emp));
    		System.out.println(allgson.toJson(emp));
    	}
    }
    
    class TableBeanEMP {
    	public static String _namefield = "name";
    	public static String _deptfield = "deptid";
    	public static String _dojfield = "dateofjoin";
    	public static String _uniquefield = "empid";
    
    	private String name;
    	private String deptid;
    	private String dateofjoin;
    	private String empid;
    
    	public TableBeanEMP() {
    
    	}
    
    	public TableBeanEMP(String name, String deptid, String dateofjoin,
    			String empid) {
    		super();
    		this.name = name;
    		this.deptid = deptid;
    		this.dateofjoin = dateofjoin;
    		this.empid = empid;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public String getDeptid() {
    		return deptid;
    	}
    
    	public void setDeptid(String deptid) {
    		this.deptid = deptid;
    	}
    
    	public String getDateofjoin() {
    		return dateofjoin;
    	}
    
    	public void setDateofjoin(String dateofjoin) {
    		this.dateofjoin = dateofjoin;
    	}
    
    	public String getEmpid() {
    		return empid;
    	}
    
    	public void setEmpid(String empid) {
    		this.empid = empid;
    	}
    
    }
    
    Output:-
    {"name":"JamesBond","deptid":"007",
    "dateofjoin":"01-01-1800","empid":"1800-007"}
    {"_namefield":"name","_deptfield":"deptid","_dojfield":"dateofjoin",
    "_uniquefield":"empid","name":"JamesBond","deptid":"007","dateofjoin":"01-01-1800","empid":"1800-007"}
    

    In the above first output doesn't have the static fileds where as second output have all.

Check this link For Examples GsonBuilder Examples like Versioning, serializeNulls, FieldNamingPolicy, enableComplexMapKeySerialization, excludeFieldsWithoutExposeAnnotation() and many more