问题 1
What is Instance Creator? Why and when do we require this?
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]]
保存以便复习
保存以便复习
收藏此条目、标记为困难题,或将其加入复习集合。
这有帮助吗?
添加评论
查看评论