Gson用户指南声明我们应该为任何类定义默认的no-args构造函数以正确使用Gson.更重要的是,在Gson 类的javadoc中,InstanceCreator如果我们尝试反序列化缺少默认构造函数的类的实例,那么将抛出异常,我们应该InstanceCreator在这种情况下使用.但是,我尝试使用缺少默认构造函数的类来测试使用Gson,并且序列化和反序列化工作都没有任何问题.
这是deserializaiton的一段代码.没有非args构造函数的类:
public class Mushroom {
private String name;
private double diameter;
public Mushroom(String name, double diameter) {
this.name = name;
this.diameter = diameter;
}
//equals(), hashCode(), etc.
}
Run Code Online (Sandbox Code Playgroud)
和测试:
@Test
public void deserializeMushroom() {
assertEquals(
new Mushroom("Fly agaric", 4.0),
new Gson().fromJson(
"{name:\"Fly agaric\", diameter:4.0}", Mushroom.class));
}
Run Code Online (Sandbox Code Playgroud)
哪个工作正常.
所以我的问题是:我是否真的可以使用Gson而不需要默认构造函数,或者在任何情况下它都不起作用?
在我的Java应用程序中,我定义了两个类,名为A,B其中B是内部类A.两者都被定义为可序列化的
public class A implements Serializable {
int attrParent;
List<B> items = new ArrayList<B>();
public void setAttrParent(int attrParent) {
this.attrParent = attrParent;
}
public int getAttrParent() {
return attrParent;
}
public class B implements Serializable {
private int attr;
public void setAttr(int attr) {
this.attr = attr;
}
public int getAttr() {
return attr;
}
public int getSomeCalculationValue() {
return this.attr * A.this.attrParent; // Problems occurs here
}
}
}
Run Code Online (Sandbox Code Playgroud)
在使用GSON序列化此对象 …