Google%20Gson%20Interview%20Questions%20and%20Answers
Question: What is Instance Creator? Why and when do we require this?Answer: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 use the above InstanceCreator 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:
- What is Google-Gson?
- How to convert Java objects to JSON format?
- What are the two ways to create Gson objects?
- What is Instance Creator? Why and when do we require this?
- How to custom Serialization and De-serialization in Gson?