Without Book Interview Questions and Answers | Online Test | Moct Test
Download Android App in your Android Device from Google Play Store
- Search for "Withoutbook Practice Exam Test" in Mobile/Tablet Play Store
Institute Training Search by Name or Email

Exams Attended

Make Homepage

Bookmark this page

Subscribe Email Address

Google Gson Interview Questions and Answers

Ques. What is Instance Creator? Why and when do we require this?
Ans.
In most of the cases, Gson library is smart enough to create instances even if any class does not provide default no-args constructor. But, if you found any problem using a class having no no-args constructor, you can use InstanceCreator support. You need to register the InstanceCreator of a java class type with Gson first before using it.

For example, Department.java does not have any default constructor.
public class Department
{
   public Department(String deptName)
   {
      this.deptName = deptName;
   }
 
   private String deptName;
 
   public String getDeptName()
   {
      return deptName;
   }
 
   public void setDeptName(String deptName)
   {
      this.deptName = deptName;
   }
    
   @Override
   public String toString()
   {
      return "Department [deptName="+deptName+"]";
   }
}

And our Employee class has reference of Department as:
public class Employee
{
   private Integer id;
   private String firstName;
   private String lastName;
   private List<String> roles;
   private Department department; //Department reference
    
   //Other setters and getters
}

To use Department class correctly, you need to register an InstanceCreator for Department.java as below:
class DepartmentInstanceCreator implements InstanceCreator<Department> {
   public Department createInstance(Type type)
   {
      return new Department("None");
   }
}
 
//Now <strong>use the above InstanceCreator</strong> as below
 
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Department.class, new DepartmentInstanceCreator());
Gson gson = gsonBuilder.create();
 
System.out.println(
            gson.fromJson("{'id':1,'firstName':'Arindam','lastName':'Ghosh','roles':['FINANCE','MANAGER'],'department':{'deptName':'Finance'}}", 
            Employee.class));
             
Output:
Employee [id=1, firstName=Arindam, lastName=Ghosh, roles=[FINANCE, MANAGER], department=Department [deptName=Finance]]
Is it helpful? Yes No

Most helpful rated by users:

©2016 WithoutBook